<commit_before><?php

class GraciousStudios_Margins_Block_Adminhtml_Sales_Margins_Grid extends Mage_Adminhtml_Block_Widget_Grid
{

    protected $avgSalePrice = 'AVG(order_item.price)';
    protected $totalQty = 'ROUND(SUM(order_item.qty_ordered))';
    protected $purchasePrice = 'ROUND(SUM(order_item.qty_ordered)) * `at_margins_purchase_price`.`value`';
    protected $salePriceExclTax = 'SUM(order_item.row_total)';
    protected $salePriceInclTax = 'SUM(order_item.row_total_incl_tax)';
    protected $margin_percentage_excl_tax;

    /**
     * GraciousStudios_Margins_Block_Adminhtml_Sales_Margins_Grid constructor.
     */
    public function __construct()
    {
        parent::__construct();
        $this->setId('margins_order_grid');
        $this->setDefaultSort('increment_id');
        $this->setDefaultDir('DESC');
        $this->setSaveParametersInSession(true);
        $this->setUseAjax(true);
        $this->margin_percentage_excl_tax = '100 - ((' . $this->purchasePrice . ' / ' . $this->salePriceExclTax . ') * 100)';
    }

    protected function _setCollectionOrder($column)
    {
        Mage::log(__METHOD__, null, 'gracious.log');
        if ($column->getOrderCallback()) {
            Mage::log('Found order callback', null, 'gracious.log');
            call_user_func($column->getOrderCallback(), $this->getCollection(), $column);
            return $this;
        }
        Mage::log('No order callback', null, 'gracious.log');
        return parent::_setCollectionOrder($column);
    }

    /**
     * @return $this
     */
    protected function _prepareCollection()
    {
        Mage::log(__METHOD__, null, 'gracious.log');
        // 100 - ((purchase_price / sale_price) * 100)
        // bruto marge
        // netto marge
        // product tax
        // total order_item_tax



        $_collection = Mage::getModel('catalog/product')
                           ->getCollection()
                           ->addAttributeToSelect(['name', 'margins_purchase_price'], 'inner')
                           ->joinTable(
                               ['order_item' => 'sales/order_item'],
                               'product_id = entity_id',
                               [
                                   'revenue_excl_tax' => $this->salePriceExclTax,
                                   'revenue_incl_tax' => $this->salePriceInclTax,
                                   'total_qty'        => $this->totalQty,
                                   'avg_sale_price'   => $this->avgSalePrice,
                                   'tax_amount'       => 'order_item.tax_amount',
                               ]
                           )
                           ->groupByAttribute('entity_id','order_item.tax_amount')
        ;
        $aCustomColumns = [
            $this->salePriceInclTax . ' - (' . $this->totalQty . ' * ' . $this->purchasePrice . ') as margin_eur',
            $this->margin_percentage_excl_tax . ' as margin_percentage_excl_tax',
            '100 - ((' . $this->purchasePrice . ' / ' . $this->salePriceInclTax . ') * 100) as margin_percentage_incl_tax',
            $this->salePriceInclTax . ' - ' . $this->purchasePrice . ' as margin_incl_eur',
            $this->salePriceExclTax . ' - ' . $this->purchasePrice . ' as margin_excl_eur',
        ];
        $sCustomColumns = implode(',', $aCustomColumns);
        $_collection->getSelect()
                    ->columns($sCustomColumns)
        ;
        $this->setCollection($_collection);
        parent::_prepareCollection();
        return $this;
    }

    /**
     * @return $this
     * @throws Exception
     */
    protected function _prepareColumns()
    {
        $helper = Mage::helper('core');
        $currency = (string)Mage::getStoreConfig(Mage_Directory_Model_Currency::XML_PATH_CURRENCY_BASE);
        $this->addColumn('entity_id', [
            'header' => $helper->__('Product ID'),
            'index'  => 'entity_id',
            'width'  => '50px',
        ]);
        $this->addColumn('name', [
            'header' => $helper->__('Product Name'),
            'index'  => 'name',
            'width'  => '200px',<commit_msg>log query<commit_after><?php

class GraciousStudios_Margins_Block_Adminhtml_Sales_Margins_Grid extends Mage_Adminhtml_Block_Widget_Grid
{

    protected $avgSalePrice = 'AVG(order_item.price)';
    protected $totalQty = 'ROUND(SUM(order_item.qty_ordered))';
    protected $purchasePrice = 'ROUND(SUM(order_item.qty_ordered)) * `at_margins_purchase_price`.`value`';
    protected $salePriceExclTax = 'SUM(order_item.row_total)';
    protected $salePriceInclTax = 'SUM(order_item.row_total_incl_tax)';
    protected $margin_percentage_excl_tax;

    /**
     * GraciousStudios_Margins_Block_Adminhtml_Sales_Margins_Grid constructor.
     */
    public function __construct()
    {
        parent::__construct();
        $this->setId('margins_order_grid');
        $this->setDefaultSort('increment_id');
        $this->setDefaultDir('DESC');
        $this->setSaveParametersInSession(true);
        $this->setUseAjax(true);
        $this->margin_percentage_excl_tax = '100 - ((' . $this->purchasePrice . ' / ' . $this->salePriceExclTax . ') * 100)';
    }

    protected function _setCollectionOrder($column)
    {
        Mage::log(__METHOD__, null, 'gracious.log');
        if ($column->getOrderCallback()) {
            Mage::log('Found order callback', null, 'gracious.log');
            call_user_func($column->getOrderCallback(), $this->getCollection(), $column);
            return $this;
        }
        Mage::log('No order callback', null, 'gracious.log');
        return parent::_setCollectionOrder($column);
    }

    /**
     * @return $this
     */
    protected function _prepareCollection()
    {
        Mage::log(__METHOD__, null, 'gracious.log');
        // 100 - ((purchase_price / sale_price) * 100)
        // bruto marge
        // netto marge
        // product tax
        // total order_item_tax



        $_collection = Mage::getModel('catalog/product')
                           ->getCollection()
                           ->addAttributeToSelect(['name', 'margins_purchase_price'], 'inner')
                           ->joinTable(
                               ['order_item' => 'sales/order_item'],
                               'product_id = entity_id',
                               [
                                   'revenue_excl_tax' => $this->salePriceExclTax,
                                   'revenue_incl_tax' => $this->salePriceInclTax,
                                   'total_qty'        => $this->totalQty,
                                   'avg_sale_price'   => $this->avgSalePrice,
                                   'tax_amount'       => 'order_item.tax_amount',
                               ]
                           )
                           ->groupByAttribute('entity_id','order_item.tax_amount')
        ;
        $aCustomColumns = [
            $this->salePriceInclTax . ' - (' . $this->totalQty . ' * ' . $this->purchasePrice . ') as margin_eur',
            $this->margin_percentage_excl_tax . ' as margin_percentage_excl_tax',
            '100 - ((' . $this->purchasePrice . ' / ' . $this->salePriceInclTax . ') * 100) as margin_percentage_incl_tax',
            $this->salePriceInclTax . ' - ' . $this->purchasePrice . ' as margin_incl_eur',
            $this->salePriceExclTax . ' - ' . $this->purchasePrice . ' as margin_excl_eur',
        ];
        $sCustomColumns = implode(',', $aCustomColumns);
        $_collection->getSelect()
                    ->columns($sCustomColumns)
        ;
        Mage::log('sql = ' . $_collection->getSelect()->__toString(), null, 'gracious.log');
        $this->setCollection($_collection);
        parent::_prepareCollection();
        return $this;
    }

    /**
     * @return $this
     * @throws Exception
     */
    protected function _prepareColumns()
    {
        $helper = Mage::helper('core');
        $currency = (string)Mage::getStoreConfig(Mage_Directory_Model_Currency::XML_PATH_CURRENCY_BASE);
        $this->addColumn('entity_id', [
            'header' => $helper->__('Product ID'),
            'index'  => 'entity_id',
            'width'  => '50px',
        ]);
        $this->addColumn('name', [
            'header' => $helper->__('Product Name'),
            'index'  => 'name',
            'width'  => '200px',
{'fraction_non_alphanumeric': 0.14003569303985722, 'fraction_numerical': 0.005472932778108269, 'mean_word_length': 1.9755752212389381, 'pattern_counts': {'":': 0, '<': 5, '<?xml version=': 0, '>': 101, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 10, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '832481', 'n_tokens_mistral': 2540, 'n_tokens_neox': 2437, 'n_words': 334}