← Back to team overview

openerp-community-reviewer team mailing list archive

lp:~camptocamp/margin-analysis/7.0-basic-improvement-and-test-jge into lp:margin-analysis

 

Joël Grand-Guillaume @ camptocamp has proposed merging lp:~camptocamp/margin-analysis/7.0-basic-improvement-and-test-jge into lp:margin-analysis.

Requested reviews:
  Pedro Manuel Baeza (pedro.baeza)

For more details, see:
https://code.launchpad.net/~camptocamp/margin-analysis/7.0-basic-improvement-and-test-jge/+merge/197684

* Improve logger
* Add a basic YML test case for product_historical_margin
* Propagate the context on browse
* Improve the usability of product_historical_margin by adding a general view in the reporting menu + adds sum in tree view
-- 
https://code.launchpad.net/~camptocamp/margin-analysis/7.0-basic-improvement-and-test-jge/+merge/197684
Your team Margin Analysis Core Editors is subscribed to branch lp:margin-analysis.
=== modified file 'product_cost_incl_bom/product_cost_incl_bom.py'
--- product_cost_incl_bom/product_cost_incl_bom.py	2013-10-10 12:11:41 +0000
+++ product_cost_incl_bom/product_cost_incl_bom.py	2013-12-04 10:48:23 +0000
@@ -22,6 +22,8 @@
 from openerp.osv.orm import Model
 from openerp.osv import fields
 import decimal_precision as dp
+import logging
+_logger = logging.getLogger(__name__)
 
 class Product(Model):
     _inherit = 'product.product'
@@ -42,11 +44,12 @@
         res = {}
         ids = ids or []
 
-        for pr in self.browse(cursor, user, ids):
+        product_without_bom_ids = []
+        for pr in self.browse(cursor, user, ids, context=context):
 
             bom_id = bom_obj._bom_find(cursor, user, pr.id, product_uom=product_uom, properties=bom_properties)
             if not bom_id: # no BoM: use standard_price
-                res[pr.id] = super(Product, self)._compute_purchase_price(cursor, user, pr.id, context=context)
+                product_without_bom_ids.append(pr.id)
                 continue
             bom = bom_obj.browse(cursor, user, bom_id)
             sub_products, routes = bom_obj._bom_explode(cursor, user, bom,
@@ -55,7 +58,7 @@
                                                         addthis=True)
             price = 0.
             for sub_product_dict in sub_products:
-                sub_product = self.browse(cursor, user, sub_product_dict['product_id'])
+                sub_product = self.browse(cursor, user, sub_product_dict['product_id'], context=context)
                 std_price = sub_product.standard_price
                 qty = uom_obj._compute_qty(cursor, user,
                                            from_uom_id = sub_product_dict['product_uom'],
@@ -69,16 +72,23 @@
                     hour = (wc.time_start + wc.time_stop + cycle * wc.time_cycle) *  (wc.time_efficiency or 1.0)
                     price += wc.costs_cycle * cycle + wc.costs_hour * hour
             price /= bom.product_qty
-            price = uom_obj._compute_price(cursor, user, bom.product_uom.id, price, bom.product_id.uom_id.id)
+            price = uom_obj._compute_price(cursor, user, bom.product_uom.id,
+                price, bom.product_id.uom_id.id, context=context)
             res[pr.id] = price
+
+        if product_without_bom_ids:
+            standard_prices = super(Product, self)._compute_purchase_price(
+                cursor, user, product_without_bom_ids, context=context)
+            res.update(standard_prices)
         return res
 
 
     def _cost_price(self, cr, uid, ids, field_name, arg, context=None):
         if context is None:
             context = {}
-
         res = self._compute_purchase_price(cr, uid, ids, context=context)
+        _logger.debug("get cost field _cost_price %s, arg: %s, context: %s, result:%s",
+            field_name, arg, context, res)
         return res
 
     _columns = {

=== modified file 'product_cost_incl_costs_with_bom/product.py'
--- product_cost_incl_costs_with_bom/product.py	2013-02-02 15:43:02 +0000
+++ product_cost_incl_costs_with_bom/product.py	2013-12-04 10:48:23 +0000
@@ -32,7 +32,7 @@
         product_uom = context.get('product_uom')
         bom_properties = context.get('properties')
         res = self._compute_purchase_price(cr, uid, ids, product_uom,
-                                           bom_properties)
+                                           bom_properties, context=context)
         for self_obj in self.browse(cr, uid, ids, context=context):
             res[self_obj.id] = res[self_obj.id] + self_obj.fixed_cost_price
         return res

=== modified file 'product_cost_incl_costs_without_bom/product.py'
--- product_cost_incl_costs_without_bom/product.py	2013-02-04 08:39:12 +0000
+++ product_cost_incl_costs_without_bom/product.py	2013-12-04 10:48:23 +0000
@@ -11,7 +11,7 @@
         if context is None:
             context = {}
         res = {}
-        for product in self.browse(cr, uid, ids):
+        for product in self.browse(cr, uid, ids, context=context):
             res[product.id] = product.standard_price + product.fixed_cost_price
         return res
 

=== modified file 'product_get_cost_field/product_get_cost_field.py'
--- product_get_cost_field/product_get_cost_field.py	2013-10-10 12:05:11 +0000
+++ product_get_cost_field/product_get_cost_field.py	2013-12-04 10:48:23 +0000
@@ -23,6 +23,7 @@
 from openerp.osv.orm import Model
 from openerp.osv import fields
 import decimal_precision as dp
+_logger = logging.getLogger(__name__)
 
 
 class Product(Model):
@@ -31,29 +32,30 @@
     def _compute_purchase_price(self, cr, uid, ids,
                                 context=None):
         res = {}
-        products = self.browse(cr, uid, ids)
         if isinstance(ids, (int, long)):
-            res = products.standard_price
-        elif isinstance(ids, list):
-            for product in self.browse(cr, uid, ids, context=context):
-                res[product.id] = product.standard_price
+            ids = [ids]
+        for product in self.browse(cr, uid, ids, context=context):
+            res[product.id] = product.standard_price
         return res
 
     def _cost_price(self, cr, uid, ids, field_name, arg, context=None):
         if context is None:
             context = {}
-        logger = logging.getLogger('product.get_cost_field')
-        logger.debug("get cost field _cost_price %s, %s, %s", field_name, arg, context)
         res = self._compute_purchase_price(cr, uid, ids, context=context)
+        _logger.debug("get cost field _cost_price %s, arg: %s, "
+                      "context: %s, result:%s",
+                      field_name, arg, context, res)
         return res
 
     def get_cost_field(self, cr, uid, ids, context=None):
-        return self._cost_price(cr, uid, ids, '', [], context)
+        return self._cost_price(cr, uid, ids, '', [], context=context)
 
     _columns = {
-        'cost_price': fields.function(_cost_price,
-                                      method=True,
-                                      string='Cost Price',
-                                      digits_compute = dp.get_precision('Sale Price'),
-                                      help="The cost price is the standard price unless you install the product_cost_incl_bom module.")
-        }
+        'cost_price': fields.function(
+            _cost_price,
+            method=True,
+            string='Cost Price',
+            digits_compute=dp.get_precision('Sale Price'),
+            help="The cost price is the standard price unless you install the "
+                 "product_cost_incl_bom module.")
+    }

=== modified file 'product_historical_margin/__openerp__.py'
--- product_historical_margin/__openerp__.py	2013-10-17 14:55:52 +0000
+++ product_historical_margin/__openerp__.py	2013-12-04 10:48:23 +0000
@@ -57,7 +57,9 @@
                 "product_view.xml",
                 ],
  'demo_xml': [],
- 'tests': [],
+ 'test': [
+    'test/basic_historical_margin.yml',
+ ],
  'installable': True,
  'auto_install': False,
  'license': 'AGPL-3',

=== modified file 'product_historical_margin/account_invoice_view.xml'
--- product_historical_margin/account_invoice_view.xml	2013-10-17 14:55:52 +0000
+++ product_historical_margin/account_invoice_view.xml	2013-12-04 10:48:23 +0000
@@ -23,21 +23,26 @@
           <field name="price_subtotal" invisible="1"/>
           <field name="subtotal_cost_price" invisible="1"/>
           <field name="company_id" invisible="1"/>
-          <field name="subtotal_company"/>
-          <field name="subtotal_cost_price_company"/>
-          <field name="margin_absolute"/>
-          <field name="margin_relative" invisible="context.get('group_by',False)"/>
+          <field name="subtotal_company" sum="Total Net Sales "/>
+          <field name="subtotal_cost_price_company" sum="Total Cost"/>
+          <field name="margin_absolute" sum="Total Absolute Margin"/>
+          <field name="margin_relative" />
         </tree>
       </field>
     </record>
 
-
     <record id="view_account_invoice_line_filter" model="ir.ui.view">
       <field name="name">account.invoice.line.select</field>
       <field name="model">account.invoice.line</field>
       <field name="arch" type="xml">
         <search string="Search Invoice Line">
-          <group>
+            <field name="product_id"/>
+            <field name="invoice_type"/>
+            <field name="partner_id"/>
+            <field name="invoice_user_id"/>
+            <field name="invoice_date"/>
+            <field name="account_id"/>
+            <field name="company_id"/>
             <filter icon="terp-go-year" string="Year" 
                 name="year"
                 domain="[('invoice_date','&lt;=', time.strftime('%%Y-%%m-%%d')),('invoice_date','&gt;=',time.strftime('%%Y-01-01'))]"
@@ -45,20 +50,12 @@
             <separator orientation="vertical"/>
             <filter icon="terp-go-month" string="Month"
                 name="month"
-                domain="[('invoice_date','&lt;=',(datetime.date.today()+relativedelta(day=31)).strftime('%%Y-%%m-%%d')),('invoice_date','&gt;=',(datetime.date.today()-relativedelta(day=1)).strftime('%%Y-%%m-%%d'))]"
+                domain="[('invoice_date','&lt;=',(context_today()+relativedelta(day=31)).strftime('%%Y-%%m-%%d')),('invoice_date','&gt;=',(context_today()-relativedelta(day=1)).strftime('%%Y-%%m-%%d'))]"
                 help="current month"/>
             <filter icon="terp-go-month" string="Month-1"
-                domain="[('invoice_date','&lt;=', (datetime.date.today() - relativedelta(day=31, months=1)).strftime('%%Y-%%m-%%d')),('invoice_date','&gt;=',(datetime.date.today() - relativedelta(day=1,months=1)).strftime('%%Y-%%m-%%d'))]"
+                domain="[('invoice_date','&lt;=', (context_today() - relativedelta(day=31, months=1)).strftime('%%Y-%%m-%%d')),('invoice_date','&gt;=',(context_today() - relativedelta(day=1,months=1)).strftime('%%Y-%%m-%%d'))]"
                 help="last month"/>
             <separator orientation="vertical"/>
-            <field name="product_id"/>
-            <field name="invoice_type"/>
-            <field name="partner_id"/>
-            <field name="invoice_user_id"/>
-            <field name="invoice_date"/>
-            <field name="account_id"/>
-            <field name="company_id"/>
-          </group>
           <newline/>
           <group expand="1" string="Group By...">
             <filter string="Partner" icon="terp-partner" domain="[]" context="{'group_by':'partner_id'}"/>
@@ -74,5 +71,20 @@
       </field>
     </record>
 
+
+    <record id="action_product_margin_details_view" model="ir.actions.act_window">
+      <field name="name">Margin Details</field>
+      <field name="res_model">account.invoice.line</field>
+      <field name="view_type">form</field>
+      <field name="view_mode">tree</field>
+      <field name="domain">[('invoice_state','in',['open', 'paid']),('invoice_type','in',['out_refund','out_invoice'])]</field>
+      <field name="context">{'search_default_product':1,'search_default_year':1}</field>
+      <field name="view_id" ref="view_invoice_line_tree_from_product"/>
+    </record>
+
+    <menuitem icon="STOCK_INDENT" action="action_product_margin_details_view"
+        id="menu_action_product_margin_details_tree"
+        parent="account.menu_finance_reporting" />
+
   </data>
 </openerp>

=== modified file 'product_historical_margin/invoice.py'
--- product_historical_margin/invoice.py	2013-11-25 10:38:14 +0000
+++ product_historical_margin/invoice.py	2013-12-04 10:48:23 +0000
@@ -22,6 +22,7 @@
 from openerp.osv.orm import Model
 from osv import fields
 import decimal_precision as dp
+_logger = logging.getLogger(__name__)
 
 class account_invoice(Model):
     _inherit = 'account.invoice'
@@ -64,11 +65,15 @@
         res = {}
         if not ids:
             return res
-        logger = logging.getLogger('product_historical_margin')
+        
+        if context is None:
+            context = {}
+        ctx = context.copy()
         user_obj = self.pool.get('res.users')
         currency_obj = self.pool.get('res.currency')
-
-        company_currency_id = user_obj.browse(cr, uid, uid, context=context).company_id.currency_id.id
+        product_obj = self.pool.get('product.product')
+        company_obj = self.pool.get('res.company')
+       
         fields = [
                 'subtotal_cost_price_company',
                 'subtotal_cost_price',
@@ -79,7 +84,22 @@
         for line_id in ids:
             res[line_id] = dict.fromkeys(fields, 0.0)
         for obj in self.browse(cr, uid, ids, context=context):
-            product = obj.product_id
+            # The company must be the one of the invoice in case a ir.cron create the invoice
+            # with admin user. We need to pass it in the context as well
+            # if we use also product_price_history with this module
+            if obj.company_id:
+                company = obj.company_id
+            else:
+                company_id = company_obj._company_default_get(
+                                                              cr,
+                                                              uid,
+                                                              'account.invoice',
+                                                              context=context)
+                company = company_obj.browse(cr, uid, company_id, context=context)
+            company_currency_id = company.currency_id.id
+            ctx['company_id'] = company.id
+            product = product_obj.read(cr, uid, obj.product_id.id,
+                                       ['id','cost_price'], context=ctx)
             if not product:
                 continue
             if obj.invoice_id.currency_id is None:
@@ -91,7 +111,7 @@
             else:
                 factor = 1.
 
-            subtotal_cost_price_company = factor * product.cost_price * obj.quantity
+            subtotal_cost_price_company = factor * product['cost_price'] * obj.quantity
             # Convert price_subtotal from invoice currency to company currency
             subtotal_company = factor * currency_obj.compute(cr, uid, currency_id,
                                                                   company_currency_id,
@@ -116,8 +136,8 @@
                 'margin_absolute': margin_absolute,
                 'margin_relative': margin_relative,
                 }
-            logger.debug("The following values has been computed for product ID %d: subtotal_cost_price=%f"
-                "subtotal_cost_price_company=%f, subtotal_company=%f", product.id, subtotal_cost_price,
+            _logger.debug("The following values has been computed for product ID %d: subtotal_cost_price=%f"
+                "subtotal_cost_price_company=%f, subtotal_company=%f", product['id'], subtotal_cost_price,
                 subtotal_cost_price_company, subtotal_company)
         return res
 
@@ -126,7 +146,7 @@
 
     def _recalc_margin_parent(self, cr, uid, ids, context=None):
         res=[]
-        for inv in self.browse(cr,uid,ids):
+        for inv in self.browse(cr, uid, ids, context=context):
             for line in inv.invoice_line:
                 res.append(line.id)
         return res
@@ -167,6 +187,7 @@
                                               multi='product_historical_margin',
                                               store=_col_store,
                                               digits_compute=dp.get_precision('Account'),
+                                              group_operator="sum",
                                               help="The Real Margin [ net sale - cost ] of the line."),
         'margin_relative': fields.function(_compute_line_values, method=True, readonly=True,type='float',
                                               string='Real Margin (%)',
@@ -203,3 +224,37 @@
         'invoice_date': fields.related('invoice_id','date_invoice',type='date',string='Invoice Date'),
 
         }
+
+    def read_group(self, cr, uid, domain, fields, groupby, 
+            offset=0, limit=None, context=None, orderby=False):
+        """The percentage of the relative margin has to be recomputed asit is nor 
+        a sum, nor a avg, but a percentage of 2 valuesof the line computed as:
+        margin_relative = margin_absolute / subtotal_company * 100"""
+        if not context:
+            context = {}
+        if groupby:
+            res = super(account_invoice_line, self).read_group(cr, uid,
+                domain, fields, groupby,
+                offset=offset, limit=limit, context=context, orderby=orderby)
+            for re in res:
+                margin_relative = 0.0
+                if re.get('margin_relative', False):
+                    # percentage of margin = (margin_absolute / subtotal_company) * 100
+                    margin_absolute = re.get('margin_absolute', 0)
+                    subtotal_company = re.get('subtotal_company', 0)
+                    if subtotal_company == 0.0:
+                        margin_relative = 999
+                    else:
+                        margin_relative = margin_absolute / subtotal_company * 100
+                    re['margin_relative'] = margin_relative
+                else:
+                    if re.get('__context', False):
+                        margin_absolute = re['__context'].get('margin_absolute', 0)
+                        subtotal_company = re.get('subtotal_company', 0)
+                        if subtotal_company == 0.0:
+                            margin_relative = 999
+                        else:
+                            margin_relative = margin_absolute / subtotal_company * 100
+                if re.get('__context', False):
+                    re['__context']['margin_relative'] = margin_relative
+        return res

=== modified file 'product_historical_margin/product_historical_margin.py'
--- product_historical_margin/product_historical_margin.py	2013-10-17 14:55:52 +0000
+++ product_historical_margin/product_historical_margin.py	2013-12-04 10:48:23 +0000
@@ -24,6 +24,7 @@
 from osv import fields
 
 import decimal_precision as dp
+_logger = logging.getLogger(__name__)
 
 # Don't Forget to remove supplier (in_invoice et in_refund) from the product margin computation
 # And remove out_refund from the computation
@@ -55,7 +56,7 @@
         if not ids:
             return res
         user_obj = self.pool.get('res.users')
-        logger = logging.getLogger('product_historical_margin')
+        
         company_id = user_obj.browse(cr, uid, uid, context=context).company_id.id
         for product_id in ids:
             res[product_id] = {'margin_absolute': 0, 'margin_relative': 0}
@@ -93,7 +94,7 @@
             tot_sale[product_id] += sale
         for product_id in tot_sale:
             if tot_sale[product_id] == 0:
-                logger.debug("Sale price for product ID %d is 0, cannot compute margin rate...", product_id)
+                _logger.debug("Sale price for product ID %d is 0, cannot compute margin rate...", product_id)
                 res[product_id]['margin_relative'] = 999.
             else:
                 res[product_id]['margin_relative'] = (res[product_id]['margin_absolute'] / tot_sale[product_id]) * 100

=== added directory 'product_historical_margin/test'
=== added file 'product_historical_margin/test/basic_historical_margin.yml'
--- product_historical_margin/test/basic_historical_margin.yml	1970-01-01 00:00:00 +0000
+++ product_historical_margin/test/basic_historical_margin.yml	2013-12-04 10:48:23 +0000
@@ -0,0 +1,129 @@
+-
+  Create a Customer for SO
+-
+  !record {model: res.partner, id: res_partner_customer01}:
+    name: Customer 3
+    customer: 1
+-
+  Create a wine product A with an avg price of 100
+-
+  !record {model: product.product, id: product_product_a_avg_01}:
+    categ_id: product.product_category_1
+    cost_method: standard
+    name: Wine A
+    standard_price: 100.0
+    list_price: 150.0
+    cost_method: average
+    uom_id: product.product_uom_unit
+    uom_po_id: product.product_uom_unit
+-
+  Create a shop
+-
+  !record {model: sale.shop, id: default_shop}:
+    name: Default test shop
+    company_id: base.main_company
+    payment_default_id: account.account_payment_term_net
+-
+  In order to test process of the Sale Order, I create sale order
+-
+  !record {model: sale.order, id: sale_order_test1}:
+    partner_id: res_partner_customer01
+    note: Invoice Manual
+    order_policy: manual
+    pricelist_id: product.list0
+    shop_id: default_shop
+    order_line: 
+      - product_id: product_product_a_avg_01
+        product_uom_qty: 10
+        price_unit: 150.0
+-
+  I confirm the Quotation with "Manual" order policy.
+-
+  !workflow {model: sale.order, action: order_confirm, ref: sale_order_test1}
+-
+  I check that Invoice should not created.
+-
+  !python {model: sale.order}: |
+    sale_order = self.browse(cr, uid, ref("sale_order_test1"))
+    assert len(sale_order.invoice_ids) == False, "Invoice should not created."
+-
+  I create advance invoice where type is 'Invoice all the Sale Order'.
+-
+  !python {model: sale.advance.payment.inv}: |
+    ctx = context.copy()
+    ctx.update({"active_model": 'sale.order', "active_ids": [ref("sale_order_test1")], "active_id":ref("sale_order_test1")})
+    pay_id = self.create(cr, uid, {'advance_payment_method': 'all'})
+    self.create_invoices(cr, uid, [pay_id], context=ctx)
+-
+  I check Invoice which made advance where type is 'Invoice all the Sale Order'.
+-
+  !python {model: sale.order}: |
+    order = self.browse(cr, uid, ref('sale_order_test1'))
+    assert order.invoice_ids, "Invoice should be created after make invoice where type is 'Invoice all the Sale Order'."
+-
+  I open the Invoice.
+-
+  !python {model: sale.order}: |
+    import netsvc
+    wf_service = netsvc.LocalService("workflow")
+    so = self.browse(cr, uid, ref("sale_order_test1"))
+    for invoice in so.invoice_ids:
+      wf_service.trg_validate(uid, 'account.invoice', invoice.id, 'invoice_open', cr)
+-
+  I check that margin of products is computed correctly
+-
+  !python {model: product.product}: |
+     value = 150 * 10 - 100 * 10
+     assert self.browse(cr, uid, ref("product_product_a_avg_01")).margin_absolute == value,"Margin for product Wine A is wrongly computed"
+-
+  In order to test process of the Sale Order, I create a second sale order
+-
+  !record {model: sale.order, id: sale_order_test2}:
+    partner_id: res_partner_customer01
+    note: Invoice Manual
+    order_policy: manual
+    pricelist_id: product.list0
+    shop_id: default_shop
+    order_line: 
+      - product_id: product_product_a_avg_01
+        product_uom_qty: 10
+        price_unit: 200
+-
+  I confirm the Quotation with "Manual" order policy.
+-
+  !workflow {model: sale.order, action: order_confirm, ref: sale_order_test2}
+-
+  I check that Invoice should not created.
+-
+  !python {model: sale.order}: |
+    sale_order = self.browse(cr, uid, ref("sale_order_test2"))
+    assert len(sale_order.invoice_ids) == False, "Invoice should not created."
+-
+  I create advance invoice where type is 'Invoice all the Sale Order'.
+-
+  !python {model: sale.advance.payment.inv}: |
+    ctx = context.copy()
+    ctx.update({"active_model": 'sale.order', "active_ids": [ref("sale_order_test2")], "active_id":ref("sale_order_test2")})
+    pay_id = self.create(cr, uid, {'advance_payment_method': 'all'})
+    self.create_invoices(cr, uid, [pay_id], context=ctx)
+-
+  I check Invoice which made advance where type is 'Invoice all the Sale Order'.
+-
+  !python {model: sale.order}: |
+    order = self.browse(cr, uid, ref('sale_order_test2'))
+    assert order.invoice_ids, "Invoice should be created after make invoice where type is 'Invoice all the Sale Order'."
+-
+  I open the Invoice.
+-
+  !python {model: sale.order}: |
+    import netsvc
+    wf_service = netsvc.LocalService("workflow")
+    so = self.browse(cr, uid, ref("sale_order_test2"))
+    for invoice in so.invoice_ids:
+      wf_service.trg_validate(uid, 'account.invoice', invoice.id, 'invoice_open', cr)
+-
+  I check that margin of products is computed correctly
+-
+  !python {model: product.product}: |
+     value = ((150 - 100) * 10 + (200 - 100) * 10 )
+     assert self.browse(cr, uid, ref("product_product_a_avg_01")).margin_absolute == value,"Margin for product Wine A is wrongly computed"

=== modified file 'product_historical_margin/wizard/historical_margin_view.xml'
--- product_historical_margin/wizard/historical_margin_view.xml	2013-10-17 14:55:52 +0000
+++ product_historical_margin/wizard/historical_margin_view.xml	2013-12-04 10:48:23 +0000
@@ -21,7 +21,7 @@
     </record>
 
     <record id="action_product_margin_view" model="ir.actions.act_window">
-      <field name="name">Product Historical Margin</field>
+      <field name="name">Margin per Product</field>
       <field name="res_model">historical.margin</field>
       <field name="view_type">form</field>
       <field name="view_mode">tree,form</field>

=== modified file 'product_standard_margin/product_std_margin.py'
--- product_standard_margin/product_std_margin.py	2013-10-14 18:16:46 +0000
+++ product_standard_margin/product_std_margin.py	2013-12-04 10:48:23 +0000
@@ -24,7 +24,7 @@
 from openerp.osv import orm, fields
 import decimal_precision as dp
 import logging
-
+_logger = logging.getLogger(__name__)
 
 class Product(orm.Model):
     _inherit = 'product.product'
@@ -43,7 +43,7 @@
         if context is None:
             context = {}
         tax_obj = self.pool.get('account.tax')
-        for prod in self.browse(cr, uid, ids):
+        for prod in self.browse(cr, uid, ids, context=context):
             price = prod.list_price
             taxes = tax_obj.compute_all(cr, uid, prod.taxes_id, price, 1, product=prod.id)
             res[prod.id] = taxes['total']
@@ -67,7 +67,7 @@
                  'margin_relative': float}
             }}
         """
-        logger = logging.getLogger('product_standard_margin')
+        
         if context is None:
             context = {}
         res = {}
@@ -75,13 +75,13 @@
             return res
         for product in ids:
             res[product] = {'margin_absolute': 0, 'margin_relative': 0}
-        for product in self.browse(cursor, user, ids):
+        for product in self.browse(cursor, user, ids, context=context):
             cost = product.cost_price
             sale = self._amount_tax_excluded(cursor, user,
                     [product.id], context=context)[product.id]
             res[product.id]['standard_margin'] = sale - cost
             if sale == 0:
-                logger.debug("Sale price for product ID %d is 0, cannot compute margin rate...", product.id)
+                _logger.debug("Sale price for product ID %d is 0, cannot compute margin rate...", product.id)
                 res[product.id]['standard_margin_rate'] = 999.
             else:
                 res[product.id]['standard_margin_rate'] = (sale - cost) / sale * 100


References