[IMP] : Removed mx.DateTime and used datetime object.
[odoo/odoo.git] / addons / procurement / schedulers.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 from datetime import datetime
24 from dateutil.relativedelta import relativedelta
25 from osv import osv
26 from tools.translate import _
27 import tools
28 import netsvc
29 import pooler
30
31 class procurement_order(osv.osv):
32     _inherit = 'procurement.order'
33
34     def _procure_confirm(self, cr, uid, ids=None, use_new_cursor=False, context=None):
35         '''
36         Call the scheduler to check the procurement order
37         
38         @param self: The object pointer
39         @param cr: The current row, from the database cursor,
40         @param uid: The current user ID for security checks
41         @param ids: List of selected IDs
42         @param use_new_cursor: False or the dbname
43         @param context: A standard dictionary for contextual values
44         @return:  Dictionary of values        
45         '''
46         if not context:
47             context = {}
48
49         try:
50             if use_new_cursor:
51                 cr = pooler.get_db(use_new_cursor).cursor()
52             wf_service = netsvc.LocalService("workflow")
53     
54             procurement_obj = self.pool.get('procurement.order')
55             if not ids:
56                 ids = procurement_obj.search(cr, uid, [], order="date_planned")
57             for id in ids:
58                 wf_service.trg_validate(uid, 'procurement.order', id, 'button_restart', cr)
59             if use_new_cursor:
60                 cr.commit()
61             company = self.pool.get('res.users').browse(cr, uid, uid, context=context).company_id
62             maxdate = (datetime.today() + relativedelta(days=company.schedule_range)).strftime(tools.DEFAULT_SERVER_DATE_FORMAT)
63             start_date = time.strftime('%Y-%m-%d, %Hh %Mm %Ss')
64             offset = 0
65             report = []
66             report_total = 0
67             report_except = 0
68             report_later = 0
69             while True:
70                 cr.execute("select id from procurement_order where state='confirmed' and procure_method='make_to_order' order by priority,date_planned limit 500 offset %s", (offset,))
71                 ids = map(lambda x: x[0], cr.fetchall())
72                 for proc in procurement_obj.browse(cr, uid, ids):
73                     if maxdate >= proc.date_planned:
74                         wf_service.trg_validate(uid, 'procurement.order', proc.id, 'button_check', cr)
75                     else:
76                         offset += 1
77                         report_later += 1
78                 for proc in procurement_obj.browse(cr, uid, ids):
79                     if proc.state == 'exception':
80                         report.append('PROC %d: on order - %3.2f %-5s - %s' % \
81                                 (proc.id, proc.product_qty, proc.product_uom.name,
82                                     proc.product_id.name))
83                         report_except += 1
84                     report_total += 1
85                 if use_new_cursor:
86                     cr.commit()
87                 if not ids:
88                     break
89             offset = 0
90             ids = []
91             while True:
92                 report_ids = []
93                 ids = procurement_obj.search(cr, uid, [('state', '=', 'confirmed'), ('procure_method', '=', 'make_to_stock')], offset=offset)
94                 for proc in procurement_obj.browse(cr, uid, ids):
95                     if maxdate >= proc.date_planned:
96                         wf_service.trg_validate(uid, 'procurement.order', proc.id, 'button_check', cr)
97                         report_ids.append(proc.id)
98                     else:
99                         report_later += 1
100                     report_total += 1
101                 for proc in procurement_obj.browse(cr, uid, report_ids):
102                     if proc.state == 'exception':
103                         report.append('PROC %d: from stock - %3.2f %-5s - %s' % \
104                                 (proc.id, proc.product_qty, proc.product_uom.name,
105                                     proc.product_id.name,))
106                         report_except += 1
107                 if use_new_cursor:
108                     cr.commit()
109                 offset += len(ids)
110                 if not ids: break
111             end_date = time.strftime('%Y-%m-%d, %Hh %Mm %Ss')
112             if uid:
113                 request = self.pool.get('res.request')
114                 summary = '''Here is the procurement scheduling report.
115     
116         Start Time: %s
117         End Time: %s
118         Total Procurements processed: %d
119         Procurements with exceptions: %d
120         Skipped Procurements (scheduled date outside of scheduler range) %d
121     
122         Exceptions:\n'''% (start_date, end_date, report_total, report_except, report_later)
123                 summary += '\n'.join(report)
124                 request.create(cr, uid,
125                     {'name': "Procurement Processing Report.",
126                         'act_from': uid,
127                         'act_to': uid,
128                         'body': summary,
129                     })
130
131             if use_new_cursor:
132                 cr.commit()
133         finally:
134             if use_new_cursor:
135                 try:
136                     cr.close()
137                 except Exception:
138                     pass
139         return {}
140
141     def create_automatic_op(self, cr, uid, context=None):
142         """
143         Create procurement of  virtual stock < 0
144         
145         @param self: The object pointer
146         @param cr: The current row, from the database cursor,
147         @param uid: The current user ID for security checks
148         @param context: A standard dictionary for contextual values
149         @return:  Dictionary of values
150         """
151         if not context:
152             context = {}
153         product_obj = self.pool.get('product.product')
154         proc_obj = self.pool.get('procurement.order')
155         warehouse_obj = self.pool.get('stock.warehouse')
156         wf_service = netsvc.LocalService("workflow")
157
158         warehouse_ids = warehouse_obj.search(cr, uid, [], context=context)
159
160         cr.execute('select id from product_product')
161         products_id = [x for x, in cr.fetchall()]
162
163         for warehouse in warehouse_obj.browse(cr, uid, warehouse_ids, context=context):
164             context['warehouse'] = warehouse
165             for product in product_obj.browse(cr, uid, products_id, context=context):
166                 if product.virtual_available >= 0.0:
167                     continue
168
169                 newdate = datetime.today()
170                 if product.supply_method == 'buy':
171                     location_id = warehouse.lot_input_id.id
172                 elif product.supply_method == 'produce':
173                     location_id = warehouse.lot_stock_id.id
174                 else:
175                     continue
176                 proc_id = proc_obj.create(cr, uid, {
177                     'name': _('Automatic OP: %s') % (product.name,),
178                     'origin': _('SCHEDULER'),
179                     'date_planned': newdate.strftime('%Y-%m-%d %H:%M:%S'),
180                     'product_id': product.id,
181                     'product_qty': -product.virtual_available,
182                     'product_uom': product.uom_id.id,
183                     'location_id': location_id,
184                     'procure_method': 'make_to_order',
185                     })
186                 wf_service.trg_validate(uid, 'procurement.order', proc_id, 'button_confirm', cr)
187                 wf_service.trg_validate(uid, 'procurement.order', proc_id, 'button_check', cr)
188
189     def _procure_orderpoint_confirm(self, cr, uid, automatic=False,\
190             use_new_cursor=False, context=None, user_id=False):
191         '''
192         Create procurement based on Orderpoint
193         use_new_cursor: False or the dbname
194         
195         @param self: The object pointer
196         @param cr: The current row, from the database cursor,
197         @param user_id: The current user ID for security checks
198         @param context: A standard dictionary for contextual values
199         @param param: False or the dbname
200         @return:  Dictionary of values
201         """        
202         '''
203         if not context:
204             context = {}
205         if use_new_cursor:
206             cr = pooler.get_db(use_new_cursor).cursor()
207         orderpoint_obj = self.pool.get('stock.warehouse.orderpoint')
208         location_obj = self.pool.get('stock.location')
209         procurement_obj = self.pool.get('procurement.order')
210         request_obj = self.pool.get('res.request')
211         wf_service = netsvc.LocalService("workflow")
212         report = []
213         offset = 0
214         ids = [1]
215         if automatic:
216             self.create_automatic_op(cr, uid, context=context)
217         while ids:
218             ids = orderpoint_obj.search(cr, uid, [], offset=offset, limit=100)
219             for op in orderpoint_obj.browse(cr, uid, ids):
220                 if op.procurement_id.state != 'exception':
221                     if op.procurement_id and op.procurement_id.purchase_id and op.procurement_id.purchase_id.state in ('draft', 'confirmed'):
222                         continue
223                 prods = location_obj._product_virtual_get(cr, uid,
224                         op.location_id.id, [op.product_id.id],
225                         {'uom': op.product_uom.id})[op.product_id.id]
226                 if prods < op.product_min_qty:
227                     qty = max(op.product_min_qty, op.product_max_qty)-prods
228                     reste = qty % op.qty_multiple
229                     if reste > 0:
230                         qty += op.qty_multiple - reste
231                     newdate = datetime.today() + relativedelta(
232                             days = int(op.product_id.seller_delay))
233                     if qty <= 0:
234                         continue
235                     if op.product_id.type not in ('consu'):
236                         proc_id = procurement_obj.create(cr, uid, {
237                             'name': op.name,
238                             'date_planned': newdate.strftime('%Y-%m-%d'),
239                             'product_id': op.product_id.id,
240                             'product_qty': qty,
241                             'product_uom': op.product_uom.id,
242                             'location_id': op.location_id.id,
243                             'procure_method': 'make_to_order',
244                             'origin': op.name
245                         })
246                         wf_service.trg_validate(uid, 'procurement.order', proc_id,
247                                 'button_confirm', cr)
248                         wf_service.trg_validate(uid, 'procurement.order', proc_id,
249                                 'button_check', cr)
250                         orderpoint_obj.write(cr, uid, [op.id],
251                                 {'procurement_id': proc_id})
252             offset += len(ids)
253             if use_new_cursor:
254                 cr.commit()
255         if user_id and report:
256             request_obj.create(cr, uid, {
257                 'name': 'Orderpoint report.',
258                 'act_from': user_id,
259                 'act_to': user_id,
260                 'body': '\n'.join(report)
261             })
262         if use_new_cursor:
263             cr.commit()
264             cr.close()
265         return {}
266
267 procurement_order()
268
269 # vim:expandtab:smartindent:tabstop=4:softtabstop=4:shiftwidth=4: