[WIP] Undo ondelete settings, work out of dropship tests
[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'), 
60         'partner_id': fields.many2one('res.partner', string = 'Partner'), #Sale should pass it here 
61         'procurement_ids': fields.many2one('procurement.order', 'group_id', 'Procurements'), 
62     }
63     _defaults = {
64         'name': lambda self, cr, uid, c: self.pool.get('ir.sequence').get(cr, uid, 'procurement.group') or ''
65     }
66
67 class procurement_rule(osv.osv):
68     '''
69     A rule describe what a procurement should do; produce, buy, move, ...
70     '''
71     _name = 'procurement.rule'
72     _description = "Procurement Rule"
73
74     def _get_action(self, cr, uid, context=None):
75         return []
76
77     _columns = {
78         'name': fields.char('Name', required=True,
79             help="This field will fill the packing origin and the name of its moves"),
80         'group_id': fields.many2one('procurement.group', 'Procurement Group'),
81         'action': fields.selection(selection=lambda s, cr, uid, context=None: s._get_action(cr, uid, context=context),
82             string='Action', required=True),
83     }
84
85
86 class procurement_order(osv.osv):
87     """
88     Procurement Orders
89     """
90     _name = "procurement.order"
91     _description = "Procurement"
92     _order = 'priority desc,date_planned'
93     _inherit = ['mail.thread']
94     _log_create = False
95     _columns = {
96         'name': fields.text('Description', required=True),
97
98         'origin': fields.char('Source Document', size=64,
99             help="Reference of the document that created this Procurement.\n"
100             "This is automatically completed by OpenERP."),
101         'company_id': fields.many2one('res.company', 'Company', required=True),
102
103         # These two fields are used for shceduling
104         'priority': fields.selection([('0', 'Not urgent'), ('1', 'Normal'), ('2', 'Urgent'), ('3', 'Very Urgent')], 'Priority', required=True, select=True),
105         'date_planned': fields.datetime('Scheduled date', required=True, select=True),
106
107         'group_id': fields.many2one('procurement.group', 'Procurement Requisition'),
108         'rule_id': fields.many2one('procurement.rule', 'Rule'),
109
110         'product_id': fields.many2one('product.product', 'Product', required=True, states={'confirmed': [('readonly', False)]}, readonly=True),
111         'product_qty': fields.float('Quantity', digits_compute=dp.get_precision('Product Unit of Measure'), required=True, states={'confirmed': [('readonly', False)]}, readonly=True),
112         'product_uom': fields.many2one('product.uom', 'Product Unit of Measure', required=True, states={'confirmed': [('readonly', False)]}, readonly=True),
113
114         'product_uos_qty': fields.float('UoS Quantity', states={'confirmed': [('readonly', False)]}, readonly=True),
115         'product_uos': fields.many2one('product.uom', 'Product UoS', states={'confirmed': [('readonly', False)]}, readonly=True),
116
117         'state': fields.selection([
118             ('cancel', 'Cancelled'),
119             ('confirmed', 'Confirmed'),
120             ('exception', 'Exception'),
121             ('running', 'Running'),
122             ('done', 'Done')
123         ], 'Status', required=True, track_visibility='onchange'),
124         'message': fields.text('Latest error', help="Exception occurred while computing procurement orders."),
125
126
127     }
128     _defaults = {
129         'state': 'confirmed',
130         'priority': '1',
131         'date_planned': lambda *a: time.strftime('%Y-%m-%d %H:%M:%S'),
132         'company_id': lambda self, cr, uid, c: self.pool.get('res.company')._company_default_get(cr, uid, 'procurement.order', context=c)
133     }
134     def onchange_product_id(self, cr, uid, ids, product_id, context=None):
135         """ Finds UoM and UoS of changed product.
136         @param product_id: Changed id of product.
137         @return: Dictionary of values.
138         """
139         if product_id:
140             w = self.pool.get('product.product').browse(cr, uid, product_id, context=context)
141             v = {
142                 'product_uom': w.uom_id.id,
143                 'product_uos': w.uos_id and w.uos_id.id or w.uom_id.id
144             }
145             return {'value': v}
146         return {}
147
148     def run(self, cr, uid, ids, context=None):
149         for procurement in self.browse(cr, uid, ids, context=context):
150             if self._assign(cr, uid, procurement, context=context):
151                 procurement.refresh()
152                 self._run(cr, uid, procurement, context=context or {})
153                 self.write(cr, uid, [procurement.id], {'state': 'running'}, context=context)
154             else:
155                 self.message_post(cr, uid, [procurement.id], body=_('No rule matching this procurement'), context=context)
156                 self.write(cr, uid, [procurement.id], {'state': 'exception'}, context=context)
157         return True
158
159     def check(self, cr, uid, ids, context=None):
160         done = []
161         for procurement in self.browse(cr, uid, ids, context=context):
162             result = self._check(cr, uid, procurement, context=context)
163             if result:
164                 self.write(cr, uid, [procurement.id], {'state': 'done'}, context=context)
165                 done.append(procurement.id)
166         return done
167
168     #
169     # Method to overwrite in different procurement modules
170     #
171     
172     def _find_suitable_rule(self, cr, uid, procurement, context=None):
173         '''This method returns a procurement.rule that depicts what to do with the given procurement
174         in order to complete its needs. It returns False if no suiting rule is found.
175             :param procurement: browse record
176             :rtype: int or False
177         '''
178         return False
179
180     def _assign(self, cr, uid, procurement, context=None):
181         '''This method check what to do with the given procurement in order to complete its needs.
182         It returns False if no solution is found, otherwise it stores the matching rule (if any) and
183         returns True.
184             :param procurement: browse record
185             :rtype: boolean
186         '''
187         rule_id = self._find_suitable_rule(cr, uid, procurement, context=context)
188         if rule_id:
189             self.write(cr, uid, [procurement.id], {'rule_id': rule_id}, context=context)
190             return True
191         return False
192
193     def _run(self, cr, uid, procurement, context=None):
194         '''This method implements the resolution of the given procurement
195             :param procurement: browse record
196         '''
197         return True
198
199     def _check(self, cr, uid, procurement, context=None):
200         '''Returns True if the given procurement is fulfilled, False otherwise
201             :param procurement: browse record
202             :rtype: boolean
203         '''
204         return False
205
206     #
207     # Scheduler
208     #
209     def run_scheduler(self, cr, uid, use_new_cursor=False, context=None):
210         '''
211         Call the scheduler to check the procurement order
212
213         @param self: The object pointer
214         @param cr: The current row, from the database cursor,
215         @param uid: The current user ID for security checks
216         @param ids: List of selected IDs
217         @param use_new_cursor: False or the dbname
218         @param context: A standard dictionary for contextual values
219         @return:  Dictionary of values
220         '''
221         if context is None:
222             context = {}
223         try:
224             if use_new_cursor:
225                 cr = openerp.registry(use_new_cursor).db.cursor()
226
227             company = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id
228             maxdate = (datetime.today() + relativedelta(days=company.schedule_range)).strftime('%Y-%m-%d %H:%M:%S')
229
230             # Run confirmed procurements
231             while True:
232                 ids = self.search(cr, uid, [('state', '=', 'confirmed'), ('date_planned', '<=', maxdate)], context=context)
233                 if not ids:
234                     break
235                 self.run(cr, uid, ids, context=context)
236                 if use_new_cursor:
237                     cr.commit()
238
239             # Check if running procurements are done
240             offset = 0
241             while True:
242                 ids = self.search(cr, uid, [('state', '=', 'running'), ('date_planned', '<=', maxdate)], offset=offset, context=context)
243                 if not ids:
244                     break
245                 done = self.check(cr, uid, ids, context=context)
246                 offset += len(ids) - len(done)
247                 if use_new_cursor and len(done):
248                     cr.commit()
249
250         finally:
251             if use_new_cursor:
252                 try:
253                     cr.close()
254                 except Exception:
255                     pass
256         return {}
257 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: