Модуль расчёта ПРИБЫЛИ для PrestaShop™ 1.5.5.0

Тема в разделе "PrestaShop", создана пользователем Jenysan, 10 сен 2013.

  1. Jenysan

    Jenysan

    Регистрация:
    1 сен 2013
    Сообщения:
    11
    Симпатии:
    3
    Здравствуйте ! Ребята , прошу помощи в разработке модуля для статистики, расчёта прибыли . Я плохо разбераюсь в написание модуля для ПШ любая помощь приветствуется любой кусочек программы сделаем модуль БСПЛАТНО . Подскажите с чего начать ? . Планирую сделать вот так . Таблица ,
    Картинка товара ,id товара , название товара , количество проданного товара , скидка , доставка , закупачная цена , цена продажи , Прибыль .
    Это столбики таблицы !
    Кнопка импорта данных статистики прибыли в формате CSV.
    Вот образец модуля для продолжения модернизации http://yadi.sk/d/cs2Yr3OM93Eiu
    --- Добавлено, 10 сен 2013 ---
    <?php

    /**
    * Statistics
    * @category stats
    *
    * @copyright PrestaShop
    * @license http://www.opensource.org/licenses/osl-3.0.php Open-source licence 3.0
    * @version 1.5
    */
    class StatsProfitMargin extends ModuleGrid
    {
    private $_html = null;
    private $_query = null;
    private $_columns = null;
    private $_defaultSortColumn = null;
    private $_emptyMessage = null;
    private $_pagingMessage = null;

    function __construct()
    {
    $this->name = 'statsprofitmargin';
    $this->tab = 'Stats';
    $this->version = 1.5;

    $this->_defaultSortColumn = 'number';
    $this->_emptyMessage = $this->l('Empty recordset returned');
    $this->_pagingMessage = $this->l('Displaying').' {0} - {1} '.$this->l('of').' {2}';

    $this->_columns = array(
    array(
    'id' => 'number',
    'header' => $this->l('ID'),
    'dataIndex' => 'number',
    'align' => 'left',
    'width' => 30
    ),
    array(
    'id' => 'total',
    'header' => $this->l('Total'),
    'dataIndex' => 'total',
    'width' => 80,
    'align' => 'left'
    ),
    // array(
    // 'id' => 'revenue',
    // 'header' => $this->l('Revenue'),
    // 'dataIndex' => 'revenue',
    // 'width' => 100,
    // 'align' => 'right'
    // ),
    array(
    'id' => 'shipping',
    'header' => $this->l('Shipping'),
    'dataIndex' => 'shipping',
    'width' => 80,
    'align' => 'left'
    ),
    array(
    'id' => 'discounts',
    'header' => $this->l('Discounts'),
    'dataIndex' => 'discounts',
    'width' => 80,
    'align' => 'left'
    ),
    array(
    'id' => 'cost',
    'header' => $this->l('Cost'),
    'dataIndex' => 'cost',
    'width' => 80,
    'align' => 'left'
    ),
    array(
    'id' => 'profit',
    'header' => $this->l('Profit'),
    'dataIndex' => 'profit',
    'width' => 80,
    'align' => 'left'
    )
    );

    parent::__construct();

    $this->displayName = $this->l('Profit margins');
    $this->description = $this->l('A list of the Profit margins');
    }

    public function install()
    {
    return (parent::install() AND $this->registerHook('AdminStatsModules'));
    }

    public function hookAdminStatsModules($params)
    {
    $engineParams = array(
    'id' => 'id_product',
    'title' => $this->displayName,
    'columns' => $this->_columns,
    'defaultSortColumn' => $this->_defaultSortColumn,
    'emptyMessage' => $this->_emptyMessage,
    'pagingMessage' => $this->_pagingMessage
    );
    $currency = new Currency(Configuration::get('PS_CURRENCY_DEFAULT'));

    $this->_html = '
    <fieldset class="width3"><legend><img src="../modules/'.$this->name.'/logo.gif" /> '.$this->displayName.'</legend>
    '.ModuleGrid::engine($engineParams).'
    </fieldset>';
    $date = $this->getDate();
    $totalprofit = $this->getTotalProfit($date) - $this->getTotalDiscounts($date);
    $totaldiscount = $this->getTotalDiscounts($date);
    $totalshipping = $this->getTotalShipping($date);
    $totalproducts = $this->getTotalProducts($date) - $this->getTotalDiscounts($date);
    $this->_html .= '<p>'.$this->l('Total profit:').' '.Tools::displayPrice($totalprofit, $currency).'</p>';
    $this->_html .= '<p>'.$this->l('Total discount:').' '.Tools::displayPrice($totaldiscount, $currency).'</p>';
    $this->_html .= '<p>'.$this->l('Total shipping:').' '.Tools::displayPrice($totalshipping, $currency).'</p>';
    $this->_html .= '<p>'.$this->l('Total product sales:').' '.Tools::displayPrice($totalproducts, $currency).'</p>';
    $this->_html .= '<p><a href="profit.csv">'.$this->l('Download CSV').'</a></p>';
    //$this->_html .= '<p>'.$this->l('Date:').' '.$date.'</p>';
    return $this->_html;
    }

    public function getTotalCount($dateBetween)
    {
    $result = Db::getInstance()->GetRow('
    SELECT COUNT(o.`id_order`) as allOrderCount
    FROM `'._DB_PREFIX_.'orders` o
    LEFT JOIN `'._DB_PREFIX_.'currency` c ON o.id_currency = c.id_currency
    '.(intval(Tools::getValue('id_country')) ? 'LEFT JOIN `'._DB_PREFIX_.'address` a ON o.id_address_delivery = a.id_address' : '').'
    WHERE o.`invoice_date` BETWEEN '.$dateBetween.'
    '.(intval(Tools::getValue('id_country')) ? 'AND a.id_country = '.intval(Tools::getValue('id_country')) : ''));
    return $result['allOrderCount'];
    }

    public function getData()
    {
    $dateBetween = $this->getDate();
    $this->_totalCount = $this->getTotalCount($dateBetween);
    $this->_query = '
    SELECT o.id_order AS number, ROUND( o.total_paid / c.conversion_rate, 2 ) AS total, ROUND( o.total_discounts / c.conversion_rate, 2 ) AS discounts, ROUND( o.total_shipping / c.conversion_rate, 2 ) AS shipping, ((
    SELECT ROUND(SUM(p.wholesale_price * od.product_quantity), 2)
    FROM '._DB_PREFIX_.'order_detail od
    LEFT JOIN '._DB_PREFIX_.'product p ON od.product_id = p.id_product
    WHERE od.id_order = o.`id_order`
    ) + (
    SELECT ROUND(SUM(IFNULL(pa.wholesale_price, 0) * od.product_quantity), 2)
    FROM '._DB_PREFIX_.'order_detail od
    LEFT JOIN '._DB_PREFIX_.'product_attribute pa ON pa.id_product_attribute = od.product_attribute_id
    WHERE od.id_order = o.`id_order`
    )) AS cost,
    ((
    SELECT ROUND(o.`total_paid` / c.`conversion_rate` - SUM(p.wholesale_price * od.product_quantity) - o.total_shipping/c.conversion_rate, 2)
    FROM '._DB_PREFIX_.'order_detail od
    LEFT JOIN '._DB_PREFIX_.'product p ON od.product_id = p.id_product
    WHERE od.id_order = o.`id_order`
    ) - (
    SELECT ROUND(SUM(IFNULL(pa.wholesale_price, 0) * od.product_quantity), 2)
    FROM '._DB_PREFIX_.'order_detail od
    LEFT JOIN '._DB_PREFIX_.'product_attribute pa ON pa.id_product_attribute = od.product_attribute_id
    WHERE od.id_order = o.`id_order`
    ) -
    (ROUND( o.total_discounts / c.conversion_rate, 2 )
    )) AS profit
    FROM `'._DB_PREFIX_.'product` p, `'._DB_PREFIX_.'product_attribute` pa, `'._DB_PREFIX_.'orders` o
    LEFT JOIN `'._DB_PREFIX_.'currency` c ON o.id_currency = c.id_currency
    WHERE o.valid =1
    AND o.total_paid <>0 AND o.`date_add` BETWEEN '.$dateBetween.'
    GROUP BY o.`id_order`';

    if (Validate::IsName($this->_sort))
    {
    $this->_query .= ' ORDER BY `'.$this->_sort.'`';
    if (isset($this->_direction))
    $this->_query .= ' '.$this->_direction;
    }
    if (($this->_start === 0 OR Validate::IsUnsignedInt($this->_start)) AND Validate::IsUnsignedInt($this->_limit))
    $this->_query .= ' LIMIT '.$this->_start.', '.($this->_limit);
    $this->_values = Db::getInstance()->ExecuteS($this->_query);

    $end = 1;
    $fp = fopen('profit.csv', 'w');
    fputcsv($fp, array($this->l('ID'), $this->l('Total'), $this->l('Discounts'), $this->l('Shipping'), $this->l('Profit'), '%'), "\t");
    foreach ($this->_values as $fields) {
    $end++;
    $fields = str_replace(".", ",", $fields);
    $fields = array_merge($fields, (array)"=(E$end/B$end)*100");;
    fputcsv($fp, $fields, "\t");
    }
    fputcsv($fp, array());
    fputcsv($fp, array($this->l('Total'), "=SUM(B2:B$end)", "=SUM(C2:C$end)", "=SUM(D2:Biggrin:$end)", "=SUM(E2:E$end)", "=AVERAGE(F2:F$end)"), "\t");
    fclose($fp);
    }



    private function getTotalProfit($dateBetween)
    {
    $result = Db::getInstance()->getRow('
    SELECT SUM((p.price + IFNULL(pa.price,0)) - (IFNULL(pa.wholesale_price,0) * od.product_quantity) + (p.wholesale_price * od.product_quantity)) as totalprofit
    FROM '._DB_PREFIX_.'orders o
    LEFT JOIN '._DB_PREFIX_.'order_detail od ON od.id_order = o.id_order
    LEFT JOIN '._DB_PREFIX_.'product p ON od.product_id = p.id_product
    LEFT JOIN '._DB_PREFIX_.'product_attribute pa ON od.product_attribute_id = pa.id_product_attribute
    WHERE o.valid = 1 AND o.total_paid <> 0 AND o.date_add BETWEEN '.$dateBetween);
    return $result['totalprofit'];
    }

    private function getTotalDiscounts($dateBetween)
    {
    $result = Db::getInstance()->getRow('
    SELECT SUM(o.total_discounts/c.conversion_rate) as totaldiscounts
    FROM '._DB_PREFIX_.'orders o
    LEFT JOIN `'._DB_PREFIX_.'currency` c ON o.id_currency = c.id_currency
    WHERE o.valid = 1 AND o.`date_add` BETWEEN '.$dateBetween);
    return $result['totaldiscounts'];
    }

    private function getTotalShipping($dateBetween)
    {
    $result = Db::getInstance()->getRow('
    SELECT SUM(o.total_shipping/c.conversion_rate) as totalshipping
    FROM '._DB_PREFIX_.'orders o
    LEFT JOIN `'._DB_PREFIX_.'currency` c ON o.id_currency = c.id_currency
    WHERE o.valid = 1 AND o.`date_add` BETWEEN '.$dateBetween);
    return $result['totalshipping'];
    }

    private function getTotalProducts($dateBetween)
    {
    $result = Db::getInstance()->getRow('
    SELECT SUM((p.price + IFNULL(pa.price,0) - (IFNULL(pa.wholesale_price, p.wholesale_price)) + (IFNULL(pa.wholesale_price, p.wholesale_price))) * od.product_quantity) as totalproducts
    FROM '._DB_PREFIX_.'orders o
    LEFT JOIN '._DB_PREFIX_.'order_detail od ON od.id_order = o.id_order
    LEFT JOIN '._DB_PREFIX_.'product p ON od.product_id = p.id_product
    LEFT JOIN '._DB_PREFIX_.'product_attribute pa ON od.product_attribute_id = pa.id_product_attribute
    WHERE o.valid = 1 AND o.total_paid <> 0 AND o.date_add BETWEEN '.$dateBetween);
    return $result['totalproducts'];
    }

    }
     
    Последнее редактирование: 10 сен 2013
    light-winged нравится это.
  2. Jenysan

    Jenysan

    Регистрация:
    1 сен 2013
    Сообщения:
    11
    Симпатии:
    3
    Точнее кнопка експорта данных статистики прибыли в формате CSV
     
  3. boltorez

    boltorez

    Регистрация:
    14 сен 2013
    Сообщения:
    5
    Симпатии:
    0
    А не проще сделать это немодулем, а отдельным скриптом? Втулить просто кнопку в админку + инпуты даты и передавать постом данные в скрипт...
     
  4. Jenysan

    Jenysan

    Регистрация:
    1 сен 2013
    Сообщения:
    11
    Симпатии:
    3
    Как вариянт хороший . Но в статистике смотреться к месту .