[IMP]stock_planning:Improvement in yml
[odoo/odoo.git] / addons / stock_planning / stock_planning.py
index 6a8b289..7e93422 100644 (file)
@@ -1,34 +1,31 @@
-# -*- encoding: utf-8 -*-
+# -*- coding: utf-8 -*-
 ##############################################################################
 #
 #    OpenERP, Open Source Management Solution
-#    Copyright (C) 2004-2008 Tiny SPRL (<http://tiny.be>). All Rights Reserved
-#    $Id$
+#    Copyright (C) 2004-2010 Tiny SPRL (<http://tiny.be>).
 #
 #    This program is free software: you can redistribute it and/or modify
-#    it under the terms of the GNU General Public License as published by
-#    the Free Software Foundation, either version 3 of the License, or
-#    (at your option) any later version.
+#    it under the terms of the GNU Affero General Public License as
+#    published by the Free Software Foundation, either version 3 of the
+#    License, or (at your option) any later version.
 #
 #    This program is distributed in the hope that it will be useful,
 #    but WITHOUT ANY WARRANTY; without even the implied warranty of
 #    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
-#    GNU General Public License for more details.
+#    GNU Affero General Public License for more details.
 #
-#    You should have received a copy of the GNU General Public License
+#    You should have received a copy of the GNU Affero General Public License
 #    along with this program.  If not, see <http://www.gnu.org/licenses/>.
 #
 ##############################################################################
 
 import time
-import mx.DateTime
-from mx.DateTime import RelativeDateTime, now, DateTime, localtime
+from datetime import datetime
+from dateutil.relativedelta import relativedelta
 
 from osv import osv, fields
 import netsvc
 from tools.translate import _
-#from tools import config
-
 
 def rounding(fl, round_value):
     if not round_value:
@@ -49,6 +46,14 @@ class stock_period(osv.osv):
     _defaults = {
         'state': 'draft'
     }
+    
+    def button_open(self, cr, uid, ids, context=None):
+        self.write(cr, uid, ids, {'state': 'open'})
+        return True
+    
+    def button_close(self, cr, uid, ids, context=None):
+        self.write(cr, uid, ids, {'state': 'close'})
+        return True
 
 stock_period()
 
@@ -61,14 +66,14 @@ class stock_sale_forecast(osv.osv):
         'company_id':fields.many2one('res.company', 'Company', required=True),
         'create_uid': fields.many2one('res.users', 'Responsible'),
         'name': fields.char('Name', size=64, readonly=True, states={'draft': [('readonly',False)]}),
-        'user_id': fields.many2one('res.users' , 'Created/Validated by',readonly=True, \
+        'user_id': fields.many2one('res.users', 'Created/Validated by',readonly=True, \
                                         help='Shows who created this forecast, or who validated.'),
-        'warehouse_id': fields.many2one('stock.warehouse' , 'Warehouse', required=True, readonly=True, states={'draft': [('readonly',False)]}, \
+        'warehouse_id': fields.many2one('stock.warehouse', 'Warehouse', required=True, readonly=True, states={'draft': [('readonly',False)]}, \
                                         help='Shows which warehouse this forecast concerns. '\
                                          'If during stock planning you will need sales forecast for all warehouses choose any warehouse now.'),
-        'period_id': fields.many2one('stock.period' , 'Period', required=True, readonly=True, states={'draft':[('readonly',False)]}, \
+        'period_id': fields.many2one('stock.period', 'Period', required=True, readonly=True, states={'draft':[('readonly',False)]}, \
                                         help = 'Shows which period this forecast concerns.'),
-        'product_id': fields.many2one('product.product' , 'Product', readonly=True, required=True, states={'draft':[('readonly',False)]}, \
+        'product_id': fields.many2one('product.product', 'Product', readonly=True, required=True, states={'draft':[('readonly',False)]}, \
                                         help = 'Shows which product this forecast concerns.'),
         'product_qty': fields.float('Product Quantity', required=True, readonly=True, states={'draft':[('readonly',False)]}, \
                                         help= 'Forecasted quantity.'),
@@ -82,13 +87,13 @@ class stock_sale_forecast(osv.osv):
 # Field used in onchange_uom to check what uom was before change and recalculate quantities acording to old uom (active_uom) and new uom.
         'active_uom': fields.many2one('product.uom',  string = "Active UoM"),
         'state': fields.selection([('draft','Draft'),('validated','Validated')],'State',readonly=True),
-        'analyzed_period1_id': fields.many2one('stock.period' , 'Period1', readonly=True, states={'draft':[('readonly',False)]},),
-        'analyzed_period2_id': fields.many2one('stock.period' , 'Period2', readonly=True, states={'draft':[('readonly',False)]},),
-        'analyzed_period3_id': fields.many2one('stock.period' , 'Period3', readonly=True, states={'draft':[('readonly',False)]},),
-        'analyzed_period4_id': fields.many2one('stock.period' , 'Period4', readonly=True, states={'draft':[('readonly',False)]},),
+        'analyzed_period1_id': fields.many2one('stock.period', 'Period1', readonly=True, states={'draft':[('readonly',False)]},),
+        'analyzed_period2_id': fields.many2one('stock.period', 'Period2', readonly=True, states={'draft':[('readonly',False)]},),
+        'analyzed_period3_id': fields.many2one('stock.period', 'Period3', readonly=True, states={'draft':[('readonly',False)]},),
+        'analyzed_period4_id': fields.many2one('stock.period', 'Period4', readonly=True, states={'draft':[('readonly',False)]},),
         'analyzed_period5_id': fields.many2one('stock.period' , 'Period5', readonly=True, states={'draft':[('readonly',False)]},),
-        'analyzed_user_id': fields.many2one('res.users' , 'This User', required=False, readonly=True, states={'draft':[('readonly',False)]},),
-        'analyzed_dept_id': fields.many2one('hr.department' , 'This Department', required=False, \
+        'analyzed_user_id': fields.many2one('res.users', 'This User', required=False, readonly=True, states={'draft':[('readonly',False)]},),
+        'analyzed_dept_id': fields.many2one('hr.department', 'This Department', required=False, \
                                     readonly=True, states={'draft':[('readonly',False)]},),
         'analyzed_warehouse_id': fields.many2one('stock.warehouse' , 'This Warehouse', required=False, \
                                     readonly=True, states={'draft':[('readonly',False)]}),
@@ -122,7 +127,7 @@ class stock_sale_forecast(osv.osv):
     }
 
     def action_validate(self, cr, uid, ids, *args):
-        self.write(cr, uid, ids, {'state':'validated','user_id':uid})
+        self.write(cr, uid, ids, {'state': 'validated','user_id': uid})
         return True
 
     def unlink(self, cr, uid, ids, context=None):
@@ -133,7 +138,7 @@ class stock_sale_forecast(osv.osv):
                 unlink_ids.append(t['id'])
             else:
                 raise osv.except_osv(_('Invalid action !'), _('Cannot delete Validated Sale Forecasts !'))
-        osv.osv.unlink(self, cr, uid, unlink_ids,context=context)
+        osv.osv.unlink(self, cr, uid, unlink_ids, context=context)
         return True
 
     def onchange_company(self, cr, uid, ids, company_id=False):
@@ -161,50 +166,48 @@ class stock_sale_forecast(osv.osv):
         res = {'value': ret}
         return res
 
-    def onchange_uom(self, cr, uid, ids, product_uom=False, product_qty=0.0, active_uom=False):
+    def onchange_uom(self, cr, uid, ids, product_uom=False, product_qty=0.0, 
+                     active_uom=False, product_id=False):
         ret = {}
-        if not ids:
-            return {}
-        if product_uom:
-            val1 = self.browse(cr, uid, ids)
-            val = val1[0]
-            coeff_uom2def = self._to_default_uom_factor(cr, uid, val, active_uom, {})
-            coeff_def2uom, round_value = self._from_default_uom_factor( cr, uid, val, product_uom, {})
+        if product_uom and product_id:
+            coeff_uom2def = self._to_default_uom_factor(cr, uid, product_id, active_uom, {})
+            coeff_def2uom, round_value = self._from_default_uom_factor(cr, uid, product_id, product_uom, {})
             coeff = coeff_uom2def * coeff_def2uom
             ret['product_qty'] = rounding(coeff * product_qty, round_value)
             ret['active_uom'] = product_uom
         return {'value': ret}
 
-    def product_amt_change(self, cr, uid, ids, product_amt = 0.0, product_uom=False):
-        ret = {}
-        if not ids:
-            return {}
+    def product_amt_change(self, cr, uid, ids, product_amt=0.0, product_uom=False, product_id=False):
         round_value = 1
-        if product_amt:
+        qty = 0.0
+        if product_amt and product_id:
+            product = self.pool.get('product.product').browse(cr, uid, product_id)
             coeff_def2uom = 1
-            val1 = self.browse(cr, uid, ids)
-            val = val1[0]
-            if (product_uom != val.product_id.uom_id.id):
-                coeff_def2uom, round_value = self._from_default_uom_factor( cr, uid, val, product_uom, {})
-            ret['product_qty'] = rounding(coeff_def2uom * product_amt/(val.product_id.product_tmpl_id.list_price), round_value)
-        res = {'value': ret}
+            if (product_uom != product.uom_id.id):
+                coeff_def2uom, round_value = self._from_default_uom_factor(cr, uid, product_id, product_uom, {})
+            qty = rounding(coeff_def2uom * product_amt/(product.product_tmpl_id.list_price), round_value)
+        res = {'value': {'product_qty': qty}}
         return res
 
-    def _to_default_uom_factor(self, cr, uid, val, uom_id, context=None):
+    def _to_default_uom_factor(self, cr, uid, product_id, uom_id, context=None):
         uom_obj = self.pool.get('product.uom')
+        product_obj = self.pool.get('product.product')
+        product = product_obj.browse(cr, uid, product_id, context=context)
         uom = uom_obj.browse(cr, uid, uom_id, context=context)
-        coef =  uom.factor
-        if uom.category_id.id <> val.product_id.uom_id.category_id.id:
-            coef = coef / val.product_id.uos_coeff
-        return val.product_id.uom_id.factor / coef
+        coef = uom.factor
+        if uom.category_id.id <> product.uom_id.category_id.id:
+            coef = coef / product.uos_coeff
+        return product.uom_id.factor / coef
 
-    def _from_default_uom_factor(self, cr, uid, val, uom_id, context):
+    def _from_default_uom_factor(self, cr, uid, product_id, uom_id, context=None):
         uom_obj = self.pool.get('product.uom')
+        product_obj = self.pool.get('product.product')
+        product = product_obj.browse(cr, uid, product_id, context=context)
         uom = uom_obj.browse(cr, uid, uom_id, context=context)
         res = uom.factor
-        if uom.category_id.id <> val.product_id.uom_id.category_id.id:
-            res = res / val.product_id.uos_coeff
-        return res / val.product_id.uom_id.factor, uom.rounding
+        if uom.category_id.id <> product.uom_id.category_id.id:
+            res = res / product.uos_coeff
+        return res / product.uom_id.factor, uom.rounding
 
     def _sales_per_users(self, cr, uid, so, so_line, company, users):
         cr.execute("SELECT sum(sol.product_uom_qty) FROM sale_order_line AS sol LEFT JOIN sale_order AS s ON (s.id = sol.order_id) " \
@@ -228,7 +231,7 @@ class stock_sale_forecast(osv.osv):
 
     def calculate_sales_history(self, cr, uid, ids, context, *args):
         sales = [[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],[0,0,0,0],]
-        for obj in self.browse(cr, uid, ids):
+        for obj in self.browse(cr, uid, ids, context=context):
             periods = obj.analyzed_period1_id, obj.analyzed_period2_id, obj.analyzed_period3_id, obj.analyzed_period4_id, obj.analyzed_period5_id
             so_obj = self.pool.get('sale.order')
             so_line_obj = self.pool.get('sale.order.line')
@@ -244,21 +247,18 @@ class stock_sale_forecast(osv.osv):
                     dept_obj = self.pool.get('hr.department')
                     dept_id =  obj.analyzed_dept_id.id and [obj.analyzed_dept_id.id] or []
                     dept_ids = dept_obj.search(cr,uid,[('parent_id','child_of',dept_id)])
-#                    dept_ids_set = ','.join(map(str,dept_ids))
-                    cr.execute("SELECT user_id FROM hr_department_user_rel WHERE (department_id IN %s)" ,(tuple(dept_ids),))
+                    cr.execute("SELECT user_id FROM resource_resource rsc, hr_employee emp WHERE (emp.resource_id = rsc.id and emp.department_id IN %s)" ,(tuple(dept_ids),))
                     dept_users = [x for x, in cr.fetchall()]
-                    dept_users_set =  ','.join(map(str,dept_users))
+                    dept_users_set =  map(str,dept_users)
                 else:
                     dept_users = False
-                factor, round_value = self._from_default_uom_factor(cr, uid, obj, obj.product_uom.id, context=context)
+                factor, round_value = self._from_default_uom_factor(cr, uid, obj.product_id.id, obj.product_uom.id, context=context)
                 for i, period in enumerate(periods):
                     if period:
                         so_period_ids = so_obj.search(cr, uid, [('date_order','>=',period.date_start),('date_order','<=',period.date_stop) ], context = context)
                         if so_period_ids:
-                           # so_period_set = ','.join(map(str,so_period_ids))
                             if obj.analyzed_user_id:
                                 user_set = str(obj.analyzed_user_id.id)
-
                                 sales[i][0] = self._sales_per_users(cr, uid, so_period_ids, so_line_product_ids, obj.company_id.id, user_set)
                                 sales[i][0] *= factor
                             if dept_users:
@@ -294,7 +294,6 @@ class stock_sale_forecast(osv.osv):
         })
         return True
 
-
 stock_sale_forecast()
 
 # The main Stock Planning object
@@ -303,8 +302,7 @@ class stock_planning(osv.osv):
     _name = "stock.planning"
 
     def _get_in_out(self, cr, uid, val, date_start, date_stop, direction, done, context=None):
-#        res = {}
-        if not context:
+        if context is None:
             context = {}
         product_obj = self.pool.get('product.product')
         mapping = {'in': {
@@ -325,16 +323,14 @@ class stock_planning(osv.osv):
         context['compute_child'] = True
         prod_id = val.product_id.id
         if done:
-            c1 = context.copy()
-            c1.update({ 'states':('done',), 'what':(direction,) })
+            context.update({ 'states':('done',), 'what':(direction,) })
             prod_ids = [prod_id]
-            st = product_obj.get_product_available(cr,uid, prod_ids, context=c1)
+            st = product_obj.get_product_available(cr, uid, prod_ids, context=context)
             res = mapping[direction]['adapter'](st.get(prod_id,0.0))
         else:
             product = product_obj.read(cr, uid, prod_id,[], context)
             product_qty = product[mapping[direction]['field']]
             res = mapping[direction]['adapter'](product_qty)
-#            res[val.id] = product_obj['incoming_qty']
         return res
 
     def _get_outgoing_before(self, cr, uid, val, date_start, date_stop, context=None):
@@ -350,13 +346,13 @@ class stock_planning(osv.osv):
         res = self._to_planning_uom(cr, uid, val, planning_qtys, context)
         return res
 
-    def _to_planning_uom(self, cr, uid, val, qtys, context):
+    def _to_planning_uom(self, cr, uid, val, qtys, context=None):
         res_qty = 0
         if qtys:
             uom_obj = self.pool.get('product.uom')
             for qty, prod_uom in qtys:
-                coef = self._to_default_uom_factor(cr, uid, val, prod_uom, context=context)
-                res_coef, round_value = self._from_default_uom_factor(cr, uid, val, val.product_uom.id, context=context)
+                coef = self._to_default_uom_factor(cr, uid, val.product_id.id, prod_uom, context=context)
+                res_coef, round_value = self._from_default_uom_factor(cr, uid, val.product_id.id, val.product_uom.id, context=context)
                 coef = coef * res_coef
                 res_qty += rounding(qty * coef, round_value)
         return res_qty
@@ -364,7 +360,7 @@ class stock_planning(osv.osv):
 
     def _get_forecast(self, cr, uid, ids, field_names, arg, context=None):
         res = {}
-        for val in self.browse(cr, uid, ids):
+        for val in self.browse(cr, uid, ids, context=context):
             res[val.id] = {}
             valid_part = val.confirmed_forecasts_only and " AND state = 'validated'" or ""
             cr.execute('SELECT sum(product_qty), product_uom  \
@@ -386,6 +382,8 @@ class stock_planning(osv.osv):
         return res
 
     def _get_stock_start(self, cr, uid, val, date, context=None):
+        if context is None:
+            context = {}
         context['from_date'] = None
         context['to_date'] = date
         locations = [val.warehouse_id.lot_stock_id.id,]
@@ -397,7 +395,7 @@ class stock_planning(osv.osv):
         res = product_obj['qty_available']     # value for stock_start
         return res
 
-    def _get_past_future(self, cr, uid, ids, field_names, arg, context):
+    def _get_past_future(self, cr, uid, ids, field_names, arg, context=None):
         res = {}
         for val in self.browse(cr, uid, ids, context=context):
             if val.period_id.date_stop < time.strftime('%Y-%m-%d'):
@@ -417,8 +415,8 @@ class stock_planning(osv.osv):
             coef = 1
             round_value = 1
             if ret[2]:
-                coef = self._to_default_uom_factor(cr, uid, val, ret[2], context)
-                res_coef, round_value = self._from_default_uom_factor(cr, uid, val, val.product_uom.id, context=context)
+                coef = self._to_default_uom_factor(cr, uid, val.product_id.id, ret[2], context)
+                res_coef, round_value = self._from_default_uom_factor(cr, uid, val.product_id.id, val.product_uom.id, context=context)
                 coef = coef * res_coef
             res[val.id]['minimum_op'] = rounding(ret[0]*coef, round_value)
             res[val.id]['maximum_op'] = ret[1]*coef
@@ -430,20 +428,17 @@ class stock_planning(osv.osv):
             result['warehouse_id'] = False
         return {'value': result}
 
-    def onchange_uom(self, cr, uid, ids, product_uom=False):
+    def onchange_uom(self, cr, uid, ids, product_uom=False, product_id=False, active_uom=False, 
+                     planned_outgoing=0.0, to_procure=0.0):
         ret = {}
         if not product_uom:
             return {}
-        if not ids:
-            return {}
-        val1 = self.browse(cr, uid, ids)
-        val = val1[0]
-        if val.active_uom:
-            coeff_uom2def = self._to_default_uom_factor(cr, uid, val, val.active_uom.id, {})
-            coeff_def2uom, round_value = self._from_default_uom_factor( cr, uid, val, product_uom, {})
+        if active_uom:
+            coeff_uom2def = self._to_default_uom_factor(cr, uid, product_id, active_uom, {})
+            coeff_def2uom, round_value = self._from_default_uom_factor(cr, uid, product_id, product_uom, {})
             coeff = coeff_uom2def * coeff_def2uom
-            ret['planned_outgoing'] = rounding(coeff * val.planned_outgoing, round_value)
-            ret['to_procure'] = rounding(coeff * val.to_procure, round_value)
+            ret['planned_outgoing'] = rounding(coeff * planned_outgoing, round_value)
+            ret['to_procure'] = rounding(coeff * to_procure, round_value)
         ret['active_uom'] = product_uom
         return {'value': ret}
 
@@ -464,9 +459,9 @@ class stock_planning(osv.osv):
         'planned_outgoing': fields.float('Planned Out', required=True,  \
                 help = 'Enter planned outgoing quantity from selected Warehouse during the selected Period of selected Product. '\
                         'To plan this value look at Confirmed Out or Sales Forecasts. This value should be equal or greater than Confirmed Out.'),
-        'company_forecast': fields.function(_get_forecast, method=True, string ='Company Forecast', multi = 'company', \
+        'company_forecast': fields.function(_get_forecast, string ='Company Forecast', multi = 'company', \
                 help = 'All sales forecasts for whole company (for all Warehouses) of selected Product during selected Period.'),
-        'warehouse_forecast': fields.function(_get_forecast, method=True, string ='Warehouse Forecast',  multi = 'warehouse',\
+        'warehouse_forecast': fields.function(_get_forecast, string ='Warehouse Forecast',  multi = 'warehouse',\
                 help = 'All sales forecasts for selected Warehouse of selected Product during selected Period.'),
         'stock_simulation': fields.float('Stock Simulation', readonly =True, \
                 help = 'Stock simulation at the end of selected Period.\n For current period it is: \n' \
@@ -485,10 +480,10 @@ class stock_planning(osv.osv):
         'to_procure': fields.float(string='Planned In', required=True, \
                 help = 'Enter quantity which (by your plan) should come in. Change this value and observe Stock simulation. ' \
                         'This value should be equal or greater than Confirmed In.'),
-        'line_time': fields.function(_get_past_future, method=True,type='char', string='Past/Future'),
-        'minimum_op': fields.function(_get_op, method=True, type='float', string = 'Minimum Rule', multi= 'minimum', \
+        'line_time': fields.function(_get_past_future,type='char', string='Past/Future'),
+        'minimum_op': fields.function(_get_op, type='float', string = 'Minimum Rule', multi= 'minimum', \
                             help = 'Minimum quantity set in Minimum Stock Rules for this Warhouse'),
-        'maximum_op': fields.function(_get_op, method=True, type='float', string = 'Maximum Rule', multi= 'maximum', \
+        'maximum_op': fields.function(_get_op, type='float', string = 'Maximum Rule', multi= 'maximum', \
                             help = 'Maximum quantity set in Minimum Stock Rules for this Warhouse'),
         'outgoing_before': fields.float('Planned Out Before', readonly=True, \
                             help= 'Planned Out in periods before calculated. '\
@@ -523,32 +518,36 @@ class stock_planning(osv.osv):
 
     _order = 'period_id'
 
-    def _to_default_uom_factor(self, cr, uid, val, uom_id, context=None):
+    def _to_default_uom_factor(self, cr, uid, product_id, uom_id, context=None):
         uom_obj = self.pool.get('product.uom')
+        product_obj = self.pool.get('product.product')
+        product = product_obj.browse(cr, uid, product_id, context=context)
         uom = uom_obj.browse(cr, uid, uom_id, context=context)
         coef = uom.factor
-        if uom.category_id.id != val.product_id.uom_id.category_id.id:
-            coef = coef / val.product_id.uos_coeff
-        return val.product_id.uom_id.factor / coef
+        if uom.category_id.id != product.uom_id.category_id.id:
+            coef = coef / product.uos_coeff
+        return product.uom_id.factor / coef
 
 
-    def _from_default_uom_factor(self, cr, uid, val, uom_id, context=None):
+    def _from_default_uom_factor(self, cr, uid, product_id, uom_id, context=None):
         uom_obj = self.pool.get('product.uom')
+        product_obj = self.pool.get('product.product')
+        product = product_obj.browse(cr, uid, product_id, context=context)
         uom = uom_obj.browse(cr, uid, uom_id, context=context)
         res = uom.factor
-        if uom.category_id.id != val.product_id.uom_id.category_id.id:
-            res = res / val.product_id.uos_coeff
-        return res / val.product_id.uom_id.factor, uom.rounding
+        if uom.category_id.id != product.uom_id.category_id.id:
+            res = res / product.uos_coeff
+        return res / product.uom_id.factor, uom.rounding
 
     def calculate_planning(self, cr, uid, ids, context, *args):
-        one_minute = RelativeDateTime(minutes=1)
-        current_date_beginning_c = mx.DateTime.today()
-        current_date_end_c = current_date_beginning_c  + RelativeDateTime(days=1, minutes=-1)  # to get hour 23:59:00
+        one_minute = relativedelta(minutes=1)
+        current_date_beginning_c = datetime.today()
+        current_date_end_c = current_date_beginning_c  + relativedelta(days=1, minutes=-1)  # to get hour 23:59:00
         current_date_beginning = current_date_beginning_c.strftime('%Y-%m-%d %H:%M:%S')
         current_date_end = current_date_end_c.strftime('%Y-%m-%d %H:%M:%S')
         for val in self.browse(cr, uid, ids, context=context):
-            day = mx.DateTime.strptime(val.period_id.date_start, '%Y-%m-%d %H:%M:%S')
-            dbefore = mx.DateTime.DateTime(day.year, day.month, day.day) - one_minute
+            day = datetime.strptime(val.period_id.date_start, '%Y-%m-%d %H:%M:%S')
+            dbefore = datetime(day.year, day.month, day.day) - one_minute
             day_before_calculated_period = dbefore.strftime('%Y-%m-%d %H:%M:%S')   # one day before start of calculated period
             cr.execute("SELECT date_start \
                     FROM stock_period AS period \
@@ -559,21 +558,22 @@ class stock_planning(osv.osv):
             date = cr.fetchone()
             start_date_current_period = date and date[0] or False
             start_date_current_period = start_date_current_period or current_date_beginning
-            day = mx.DateTime.strptime(start_date_current_period, '%Y-%m-%d %H:%M:%S')
-            dbefore = mx.DateTime.DateTime(day.year, day.month, day.day) - one_minute
+            
+            day = datetime.strptime(start_date_current_period, '%Y-%m-%d %H:%M:%S')
+            dbefore = datetime(day.year, day.month, day.day) - one_minute
             date_for_start = dbefore.strftime('%Y-%m-%d %H:%M:%S')   # one day before current period
-            already_out = self._get_in_out(cr, uid, val, start_date_current_period, current_date_end, direction='out', done = True, context=context),
-            already_in = self._get_in_out(cr, uid, val, start_date_current_period, current_date_end, direction='in', done = True, context=context),
-            outgoing = self._get_in_out(cr, uid, val, val.period_id.date_start, val.period_id.date_stop, direction='out', done = False, context=context),
-            incoming = self._get_in_out(cr, uid, val, val.period_id.date_start, val.period_id.date_stop, direction='in', done = False, context=context),
+            already_out = self._get_in_out(cr, uid, val, start_date_current_period, current_date_end, direction='out', done=True, context=context),
+            already_in = self._get_in_out(cr, uid, val, start_date_current_period, current_date_end, direction='in', done=True, context=context),
+            outgoing = self._get_in_out(cr, uid, val, val.period_id.date_start, val.period_id.date_stop, direction='out', done=False, context=context),
+            incoming = self._get_in_out(cr, uid, val, val.period_id.date_start, val.period_id.date_stop, direction='in', done=False, context=context),
             outgoing_before = self._get_outgoing_before(cr, uid, val, start_date_current_period, day_before_calculated_period, context=context),
-            incoming_before = self._get_in_out(cr, uid, val, start_date_current_period, day_before_calculated_period, direction='in', done = False, context=context),
+            incoming_before = self._get_in_out(cr, uid, val, start_date_current_period, day_before_calculated_period, direction='in', done=False, context=context),
             stock_start = self._get_stock_start(cr, uid, val, date_for_start, context=context),
             if start_date_current_period == val.period_id.date_start:   # current period is calculated
                 current = True
             else:
                 current = False
-            factor, round_value = self._from_default_uom_factor(cr, uid, val, val.product_uom.id, context=context)
+            factor, round_value = self._from_default_uom_factor(cr, uid, val.product_id.id, val.product_uom.id, context=context)
             self.write(cr, uid, ids, {
                 'already_out': rounding(already_out[0]*factor,round_value),
                 'already_in': rounding(already_in[0]*factor,round_value),
@@ -594,7 +594,7 @@ class stock_planning(osv.osv):
 # so if UoM is from UoM category it is used as UoM in standard and if product has UoS the UoS will be calcualated.
 # If UoM is from UoS category it is recalculated to basic UoS from product (in planning you can use any UoS from UoS category)
 # and basic UoM is calculated.
-    def _qty_to_standard(self, cr, uid, val, context):
+    def _qty_to_standard(self, cr, uid, val, context=None):
         uos = False
         uos_qty = 0.0
         if val.product_uom.category_id.id == val.product_id.uom_id.category_id.id:
@@ -602,29 +602,29 @@ class stock_planning(osv.osv):
             uom = val.product_uom.id
             if val.product_id.uos_id:
                 uos = val.product_id.uos_id.id
-                coeff_uom2def = self._to_default_uom_factor(cr, uid, val, val.product_uom.id, {})
-                coeff_def2uom, round_value = self._from_default_uom_factor(cr, uid, val, uos, {})
+                coeff_uom2def = self._to_default_uom_factor(cr, uid, val.product_id.id, val.product_uom.id, {})
+                coeff_def2uom, round_value = self._from_default_uom_factor(cr, uid, val.product_id.id, uos, {})
                 uos_qty = rounding(val.incoming_left * coeff_uom2def * coeff_def2uom, round_value)
         elif val.product_uom.category_id.id == val.product_id.uos_id.category_id.id:
-            coeff_uom2def = self._to_default_uom_factor(cr, uid, val, val.product_uom.id, {})
+            coeff_uom2def = self._to_default_uom_factor(cr, uid, val.product_id.id, val.product_uom.id, {})
             uos = val.product_id.uos_id.id
-            coeff_def2uom, round_value = self._from_default_uom_factor(cr, uid, val, uos, {})
+            coeff_def2uom, round_value = self._from_default_uom_factor(cr, uid, val.product_id.id, uos, {})
             uos_qty = rounding(val.incoming_left * coeff_uom2def * coeff_def2uom, round_value)
             uom = val.product_id.uom_id.id
-            coeff_def2uom, round_value = self._from_default_uom_factor(cr, uid, val, uom, {})
+            coeff_def2uom, round_value = self._from_default_uom_factor(cr, uid, val.product_id.id, uom, {})
             uom_qty = rounding(val.incoming_left * coeff_uom2def * coeff_def2uom, round_value)
         return uom_qty, uom, uos_qty, uos
 
     def procure_incomming_left(self, cr, uid, ids, context, *args):
-        for obj in self.browse(cr, uid, ids):
+        for obj in self.browse(cr, uid, ids, context=context):
             if obj.incoming_left <= 0:
                 raise osv.except_osv(_('Error !'), _('Incoming Left must be greater than 0 !'))
             uom_qty, uom, uos_qty, uos = self._qty_to_standard(cr, uid, obj, context)
-            user = self.pool.get('res.users').browse(cr, uid, uid, context)
+            user = self.pool.get('res.users').browse(cr, uid, uid, context=context)
             proc_id = self.pool.get('procurement.order').create(cr, uid, {
                         'company_id' : obj.company_id.id,
-                        'name': _('Manual planning for ') + obj.period_id.name,
-                        'origin': _('MPS(') + str(user.login) +') '+ obj.period_id.name,
+                        'name': _('Manual planning for %s') %(obj.period_id.name),
+                        'origin': _('MPS(%s) %s') %(user.login, obj.period_id.name),
                         'date_planned': obj.period_id.date_start,
                         'product_id': obj.product_id.id,
                         'product_qty': uom_qty,
@@ -633,32 +633,34 @@ class stock_planning(osv.osv):
                         'product_uos': uos,
                         'location_id': obj.procure_to_stock and obj.warehouse_id.lot_stock_id.id or obj.warehouse_id.lot_input_id.id,
                         'procure_method': 'make_to_order',
-                        'note' : _("Procurement created in MPS by user: ") + str(user.login) + _("  Creation Date: ") + \
-                                            time.strftime('%Y-%m-%d %H:%M:%S') + \
-                                        _("\nFor period: ") + obj.period_id.name + _(" according to state:") + \
-                                        _("\n Warehouse Forecast: ") + str(obj.warehouse_forecast) + \
-                                        _("\n Initial Stock: ") + str(obj.stock_start) + \
-                                        _("\n Planned Out: ") + str(obj.planned_outgoing) + _("    Planned In: ") + str(obj.to_procure) + \
-                                        _("\n Already Out: ") + str(obj.already_out) + _("    Already In: ") +  str(obj.already_in) + \
-                                        _("\n Confirmed Out: ") + str(obj.outgoing) + _("    Confirmed In: ") + str(obj.incoming) + \
-                                        _("\n Planned Out Before: ") + str(obj.outgoing_before) + _("    Confirmed In Before: ") + \
-                                                                                            str(obj.incoming_before) + \
-                                        _("\n Expected Out: ") + str(obj.outgoing_left) + _("    Incoming Left: ") + str(obj.incoming_left) + \
-                                        _("\n Stock Simulation: ") +  str(obj.stock_simulation) + _("    Minimum stock: ") + str(obj.minimum_op),
-
+                        'note' : _(' Procurement created in MPS by user: %s   Creation Date: %s \
+                                        \n For period: %s \
+                                        \n according to state: \
+                                        \n Warehouse Forecast: %s \
+                                        \n Initial Stock: %s \
+                                        \n Planned Out: %s    Planned In: %s \
+                                        \n Already Out: %s    Already In: %s \
+                                        \n Confirmed Out: %s    Confirmed In: %s \
+                                        \n Planned Out Before: %s    Confirmed In Before: %s \
+                                        \n Expected Out: %s    Incoming Left: %s \
+                                        \n Stock Simulation: %s    Minimum stock: %s') %(user.login, time.strftime('%Y-%m-%d %H:%M:%S'),
+                                        obj.period_id.name, obj.warehouse_forecast, obj.planned_outgoing, obj.stock_start, obj.to_procure,
+                                        obj.already_out, obj.already_in, obj.outgoing, obj.incoming, obj.outgoing_before, obj.incoming_before,
+                                        obj.outgoing_left, obj.incoming_left, obj.stock_simulation, obj.minimum_op)
                             }, context=context)
             wf_service = netsvc.LocalService("workflow")
             wf_service.trg_validate(uid, 'procurement.order', proc_id, 'button_confirm', cr)
             self.calculate_planning(cr, uid, ids, context)
             prev_text = obj.history or ""
             self.write(cr, uid, ids, {
-                    'history' : prev_text + _('Requisition (') + str(user.login) + ", " + time.strftime('%Y.%m.%d %H:%M) ') + str(obj.incoming_left) + \
-                    " " + obj.product_uom.name + "\n",
+                    'history': _('%s Requisition (%s,  %s) %s %s \n') % (prev_text, user.login, time.strftime('%Y.%m.%d %H:%M'),
+                    obj.incoming_left, obj.product_uom.name)
                 })
+
         return True
 
     def internal_supply(self, cr, uid, ids, context, *args):
-        for obj in self.browse(cr, uid, ids):
+        for obj in self.browse(cr, uid, ids, context=context):
             if obj.incoming_left <= 0:
                 raise osv.except_osv(_('Error !'), _('Incoming Left must be greater than 0 !'))
             if not obj.supply_warehouse_id:
@@ -668,32 +670,34 @@ class stock_planning(osv.osv):
             uom_qty, uom, uos_qty, uos = self._qty_to_standard(cr, uid, obj, context)
             user = self.pool.get('res.users').browse(cr, uid, uid, context)
             picking_id = self.pool.get('stock.picking').create(cr, uid, {
-                            'origin': _('MPS(') + str(user.login) +') '+ obj.period_id.name,
-                            'type': 'internal',
-                            'state': 'auto',
-                            'date' : obj.period_id.date_start,
-                            'move_type': 'direct',
-                            'invoice_state':  'none',
-                            'company_id': obj.company_id.id,
-                            'note': _("Pick created from MPS by user: ") + str(user.login) + _("  Creation Date: ") + \
-                                            time.strftime('%Y-%m-%d %H:%M:%S') + \
-                                        _("\nFor period: ") + obj.period_id.name + _(" according to state:") + \
-                                        _("\n Warehouse Forecast: ") + str(obj.warehouse_forecast) + \
-                                        _("\n Initial Stock: ") + str(obj.stock_start) + \
-                                        _("\n Planned Out: ") + str(obj.planned_outgoing) + _("    Planned In: ") + str(obj.to_procure) + \
-                                        _("\n Already Out: ") + str(obj.already_out) + _("    Already In: ") +  str(obj.already_in) + \
-                                        _("\n Confirmed Out: ") + str(obj.outgoing) + _("    Confirmed In: ") + str(obj.incoming) + \
-                                        _("\n Planned Out Before: ") + str(obj.outgoing_before) + _("    Confirmed In Before: ") + \
-                                                                                            str(obj.incoming_before) + \
-                                        _("\n Expected Out: ") + str(obj.outgoing_left) + _("    Incoming Left: ") + str(obj.incoming_left) + \
-                                        _("\n Stock Simulation: ") +  str(obj.stock_simulation) + _("    Minimum stock: ") + str(obj.minimum_op),
+                        'origin': _('MPS(%s) %s') %(user.login, obj.period_id.name),
+                        'type': 'internal',
+                        'state': 'auto',
+                        'date': obj.period_id.date_start,
+                        'move_type': 'direct',
+                        'invoice_state':  'none',
+                        'company_id': obj.company_id.id,
+                        'note': _('Pick created from MPS by user: %s   Creation Date: %s \
+                                    \nFor period: %s   according to state: \
+                                    \n Warehouse Forecast: %s \
+                                    \n Initial Stock: %s \
+                                    \n Planned Out: %s  Planned In: %s \
+                                    \n Already Out: %s  Already In: %s \
+                                    \n Confirmed Out: %s   Confirmed In: %s \
+                                    \n Planned Out Before: %s   Confirmed In Before: %s \
+                                    \n Expected Out: %s   Incoming Left: %s \
+                                    \n Stock Simulation: %s   Minimum stock: %s ')
+                                    % (user.login, time.strftime('%Y-%m-%d %H:%M:%S'), obj.period_id.name, obj.warehouse_forecast,
+                                       obj.stock_start, obj.planned_outgoing, obj.to_procure, obj.already_out, obj.already_in,
+                                       obj.outgoing, obj.incoming, obj.outgoing_before, obj.incoming_before,
+                                       obj.outgoing_left, obj.incoming_left, obj.stock_simulation, obj.minimum_op)
                         })
 
             move_id = self.pool.get('stock.move').create(cr, uid, {
-                        'name': _('MPS(') + str(user.login) +') '+ obj.period_id.name,
+                        'name': _('MPS(%s) %s') %(user.login, obj.period_id.name),
                         'picking_id': picking_id,
                         'product_id': obj.product_id.id,
-                        'date_planned': obj.period_id.date_start,
+                        'date': obj.period_id.date_start,
                         'product_qty': uom_qty,
                         'product_uom': uom,
                         'product_uos_qty': uos_qty,
@@ -712,8 +716,8 @@ class stock_planning(osv.osv):
         prev_text = obj.history or ""
         pick_name = self.pool.get('stock.picking').browse(cr, uid, picking_id).name
         self.write(cr, uid, ids, {
-              'history' : prev_text + _('Pick List ')+ pick_name + " (" + str(user.login) + ", " + time.strftime('%Y.%m.%d %H:%M) ') \
-                + str(obj.incoming_left) +" " + obj.product_uom.name + "\n",
+                    'history': _('%s Pick List %s (%s,  %s) %s %s \n') % (prev_text, pick_name, user.login, time.strftime('%Y.%m.%d %H:%M'),
+                    obj.incoming_left, obj.product_uom.name)
                 })
 
         return True