[IMP] Change move_id in move_dest_id where needed (thanks to branch of psi), give...
[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 import time
23
24 from datetime import datetime
25 from dateutil.relativedelta import relativedelta
26
27 from openerp.osv import fields, osv
28 import openerp.addons.decimal_precision as dp
29 from openerp.tools.translate import _
30 import openerp
31
32 class procurement_group(osv.osv):
33     '''
34     The procurement requirement class is used to group products together
35     when computing procurements. (tasks, physical products, ...)
36
37     The goal is that when you have one sale order of several products
38     and the products are pulled from the same or several location(s), to keep
39     having the moves grouped into pickings that represent the sale order.
40
41     Used in: sales order (to group delivery order lines like the so), pull/push
42     rules (to pack like the delivery order), on orderpoints (e.g. for wave picking
43     all the similar products together).
44
45     Grouping is made only if the source and the destination is the same.
46     Suppose you have 4 lines on a picking from Output where 2 lines will need
47     to come from Input (crossdock) and 2 lines coming from Stock -> Output As
48     the four procurement orders will have the same group ids from the SO, the
49     move from input will have a stock.picking with 2 grouped lines and the move
50     from stock will have 2 grouped lines also.
51
52     The name is usually the name of the original document (sale order) or a
53     sequence computed if created manually.
54     '''
55     _name = 'procurement.group'
56     _description = 'Procurement Requisition'
57     _order = "id desc"
58     _columns = {
59         'name': fields.char('Reference', required=True), 
60         'move_type': fields.selection([
61             ('direct', 'Partial'), ('one', 'All at once')],
62             'Delivery Method', required=True),
63         'partner_id': fields.many2one('res.partner', string = 'Partner'), #Sale should pass it here 
64         'procurement_ids': fields.one2many('procurement.order', 'group_id', 'Procurements'), 
65     }
66     _defaults = {
67         'name': lambda self, cr, uid, c: self.pool.get('ir.sequence').get(cr, uid, 'procurement.group') or '',
68         'move_type': lambda self, cr, uid, c: 'one'
69     }
70
71 class procurement_rule(osv.osv):
72     '''
73     A rule describe what a procurement should do; produce, buy, move, ...
74     '''
75     _name = 'procurement.rule'
76     _description = "Procurement Rule"
77
78     def _get_action(self, cr, uid, context=None):
79         return []
80
81     _columns = {
82         'name': fields.char('Name', required=True,
83             help="This field will fill the packing origin and the name of its moves"),
84         'group_id': fields.many2one('procurement.group', 'Procurement Group'),
85         'action': fields.selection(selection=lambda s, cr, uid, context=None: s._get_action(cr, uid, context=context),
86             string='Action', required=True),
87     }
88
89
90 class procurement_order(osv.osv):
91     """
92     Procurement Orders
93     """
94     _name = "procurement.order"
95     _description = "Procurement"
96     _order = 'priority desc,date_planned'
97     _inherit = ['mail.thread']
98     _log_create = False
99     _columns = {
100         'name': fields.text('Description', required=True),
101
102         'origin': fields.char('Source Document', size=64,
103             help="Reference of the document that created this Procurement.\n"
104             "This is automatically completed by OpenERP."),
105         'company_id': fields.many2one('res.company', 'Company', required=True),
106
107         # These two fields are used for shceduling
108         'priority': fields.selection([('0', 'Not urgent'), ('1', 'Normal'), ('2', 'Urgent'), ('3', 'Very Urgent')], 'Priority', required=True, select=True),
109         'date_planned': fields.datetime('Scheduled date', required=True, select=True),
110
111         'group_id': fields.many2one('procurement.group', 'Procurement Requisition'),
112         'rule_id': fields.many2one('procurement.rule', 'Rule'),
113
114         'product_id': fields.many2one('product.product', 'Product', required=True, states={'confirmed': [('readonly', False)]}, readonly=True),
115         'product_qty': fields.float('Quantity', digits_compute=dp.get_precision('Product Unit of Measure'), required=True, states={'confirmed': [('readonly', False)]}, readonly=True),
116         'product_uom': fields.many2one('product.uom', 'Product Unit of Measure', required=True, states={'confirmed': [('readonly', False)]}, readonly=True),
117
118         'product_uos_qty': fields.float('UoS Quantity', states={'confirmed': [('readonly', False)]}, readonly=True),
119         'product_uos': fields.many2one('product.uom', 'Product UoS', states={'confirmed': [('readonly', False)]}, readonly=True),
120
121         'state': fields.selection([
122             ('cancel', 'Cancelled'),
123             ('confirmed', 'Confirmed'),
124             ('exception', 'Exception'),
125             ('running', 'Running'),
126             ('done', 'Done')
127         ], 'Status', required=True, track_visibility='onchange'),
128         'message': fields.text('Latest error', help="Exception occurred while computing procurement orders.", track_visibility='onchange'),
129     }
130
131     _defaults = {
132         'state': 'confirmed',
133         'priority': '1',
134         'date_planned': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),
135         'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'procurement.order', context=c)
136     }
137     def onchange_product_id(self, cr, uid, ids, product_id, context=None):
138         """ Finds UoM and UoS of changed product.
139         @param product_id: Changed id of product.
140         @return: Dictionary of values.
141         """
142         if product_id:
143             w = self.pool.get('product.product').browse(cr, uid, product_id, context=context)
144             v = {
145                 'product_uom': w.uom_id.id,
146                 'product_uos': w.uos_id and w.uos_id.id or w.uom_id.id
147             }
148             return {'value': v}
149         return {}
150
151     def cancel(self, cr, uid, ids, context=None):
152         self.write(cr, uid, ids, {'state': 'cancel'}, context=context)
153         return True
154
155     def run(self, cr, uid, ids, context=None):
156         for procurement in self.browse(cr, uid, ids, context=context):
157             if self._assign(cr, uid, procurement, context=context):
158                 procurement.refresh()
159                 self._run(cr, uid, procurement, context=context or {})
160                 self.write(cr, uid, [procurement.id], {'state': 'running'}, context=context)
161             else:
162                 self.message_post(cr, uid, [procurement.id], body=_('No rule matching this procurement'), context=context)
163                 self.write(cr, uid, [procurement.id], {'state': 'exception'}, context=context)
164         return True
165
166     def check(self, cr, uid, ids, context=None):
167         done = []
168         for procurement in self.browse(cr, uid, ids, context=context):
169             result = self._check(cr, uid, procurement, context=context)
170             if result:
171                 self.write(cr, uid, [procurement.id], {'state': 'done'}, context=context)
172                 done.append(procurement.id)
173         return done
174
175     #
176     # Method to overwrite in different procurement modules
177     #
178     def _find_suitable_rule(self, cr, uid, procurement, context=None):
179         '''This method returns a procurement.rule that depicts what to do with the given procurement
180         in order to complete its needs. It returns False if no suiting rule is found.
181             :param procurement: browse record
182             :rtype: int or False
183         '''
184         return False
185
186     def _assign(self, cr, uid, procurement, context=None):
187         '''This method check what to do with the given procurement in order to complete its needs.
188         It returns False if no solution is found, otherwise it stores the matching rule (if any) and
189         returns True.
190             :param procurement: browse record
191             :rtype: boolean
192         '''
193         rule_id = self._find_suitable_rule(cr, uid, procurement, context=context)
194         if rule_id:
195             self.write(cr, uid, [procurement.id], {'rule_id': rule_id}, context=context)
196             return True
197         return False
198
199     def _run(self, cr, uid, procurement, context=None):
200         '''This method implements the resolution of the given procurement
201             :param procurement: browse record
202         '''
203         return True
204
205     def _check(self, cr, uid, procurement, context=None):
206         '''Returns True if the given procurement is fulfilled, False otherwise
207             :param procurement: browse record
208             :rtype: boolean
209         '''
210         return False
211
212     #
213     # Scheduler
214     #
215     def run_scheduler(self, cr, uid, use_new_cursor=False, context=None):
216         '''
217         Call the scheduler to check the procurement order
218
219         @param self: The object pointer
220         @param cr: The current row, from the database cursor,
221         @param uid: The current user ID for security checks
222         @param ids: List of selected IDs
223         @param use_new_cursor: False or the dbname
224         @param context: A standard dictionary for contextual values
225         @return:  Dictionary of values
226         '''
227         if context is None:
228             context = {}
229         try:
230             if use_new_cursor:
231                 cr = openerp.registry(use_new_cursor).db.cursor()
232
233             company = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id
234             maxdate = (datetime.today() + relativedelta(days=company.schedule_range)).strftime('%Y-%m-%d %H:%M:%S')
235
236             # Run confirmed procurements
237             while True:
238                 ids = self.search(cr, uid, [('state', '=', 'confirmed'), ('date_planned', '<=', maxdate)], context=context)
239                 if not ids:
240                     break
241                 self.run(cr, uid, ids, context=context)
242                 if use_new_cursor:
243                     cr.commit()
244
245             # Check if running procurements are done
246             offset = 0
247             while True:
248                 ids = self.search(cr, uid, [('state', '=', 'running'), ('date_planned', '<=', maxdate)], offset=offset, context=context)
249                 if not ids:
250                     break
251                 done = self.check(cr, uid, ids, context=context)
252                 offset += len(ids) - len(done)
253                 if use_new_cursor and len(done):
254                     cr.commit()
255
256         finally:
257             if use_new_cursor:
258                 try:
259                     cr.close()
260                 except Exception:
261                     pass
262         return {}
263 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: