Рассчитать стоимость каждого товара в заказе в Magento - PullRequest
1 голос
/ 12 декабря 2010

Я хочу рассчитать базовую цену всех товаров в заказе. Цена за каждое (1 количество) должна включать любые скидки / бонусы, но НЕ налог. Сумма всех цен на товары, умноженная на их количество и налог, должна совпадать с $ order-> getGrandTotal ().

Мне удалось получить индивидуальные цены, включая стоимость доставки, с небольшой погрешностью. Конечно, это не приемлемо при работе с валютой. Также я не принял во внимание продукты в комплекте и тому подобное.

Поэтому я прошу вас помочь мне, мне нужно сделать тот же расчет, что и в Magento, и при этом получить те значения, которые мне нужны (каждый продукт / доставка со скидками, но без налога).

Заранее спасибо

1 Ответ

4 голосов
/ 15 декабря 2010

Я сделал это, и это дает мне именно ту информацию, которая мне нужна.Но я не уверен, что это правильный способ сделать это.Кроме того, мой $ total, похоже, отличается от $ grand_total с несколькими десятичными знаками, такими как 0,005 или иногда похожими.

<code>$store = Mage::app()->getStore($order->getStoreId());

$customer = Mage::getModel('customer/customer')
    ->load($order->getCustomerId());

$tax_calc = Mage::getSingleton('tax/calculation');

$tax_rate_req = $tax_calc->getRateRequest(
    $order->getShippingAddress(), 
    $order->getBillingAddress(), 
    $customer->getTaxClassId(), 
    $store);

$args = array();
$total = 0;

// Calculate price of each item in the order
foreach($order->getAllVisibleItems() as $item)
{
    $product = Mage::getModel('catalog/product')
        ->load($item->getProductId());

    $children = $item->getChildrenItems();

    if(count($children) && ($product->getData('price_type') != 1))
    {
        foreach($children as $child)
        {
            $product = Mage::getModel('catalog/product')
                ->load($child->getProductId());

            /* If tax_percent is not set?
            Mage::getSingleton('tax/calculation')->getRate(
                $tax_rate_req->setProductClassId($product->getTaxClassId()))
            */
            $tax_mod = (float)$child->getData('tax_percent');
            $tax_mod /= 100;

            $qty = (float)$child->getData('qty_ordered');

            $price = (float)$child->getData('row_total_incl_tax');
            $price -= (float)$child->getData('discount_amount');

            $base_price = (($price / (1 + $tax_mod)) / $qty);
            $base_price = $store->roundPrice($base_price);

            $total += (($base_price * (1 + $tax_mod)) * $qty);

            $args[] = array
                (
                    'name'          => $product->getData('name'),
                    'sku'           => $child->getData('sku'),
                    'tax_mod'       => $tax_mod,
                    'qty'           => $qty,
                    'price'         => $price,
                    'base_price'    => $base_price
                );
        }
    }
    else
    {
        /* If tax_percent is not set?
        Mage::getSingleton('tax/calculation')->getRate(
            $tax_rate_req->setProductClassId($product->getTaxClassId()))
        */
        $tax_mod = (float)$item->getData('tax_percent');
        $tax_mod /= 100;

        $qty = (float)$item->getData('qty_ordered');

        $price = (float)$item->getData('row_total_incl_tax');
        $price -= (float)$item->getData('discount_amount');

        $base_price = (($price / (1 + $tax_mod)) / $qty);
        $base_price = $store->roundPrice($base_price);

        $total += (($base_price * (1 + $tax_mod)) * $qty);

        $args[] = array
            (
                'name'          => $product->getData('name'),
                'sku'           => $item->getData('sku'),
                'tax_mod'       => $tax_mod,
                'qty'           => $qty,
                'price'         => $price,
                'base_price'    => $base_price
            );
    }
}

// Calculate price for shipping
if(($price = (float)$order->getData('shipping_incl_tax')) > 0)
{
    $tax_mod = $tax_calc->getRate($tax_rate_req->setProductClassId(
        Mage::getStoreConfig('tax/classes/shipping_tax_class')));
    $tax_mod /= 100;

    $price -= (float)$order->getData('shipping_discount_amount');

    $base_price = ($price / (1 + $tax_mod));

    $base_price = $store->roundPrice($base_price);

    $total += ($base_price * (1 + $tax_mod));

    $args[] = array
        (
            'name'          => $order->getData('shipping_description'),
            'sku'           => $order->getData('shipping_method'),
            'tax_mod'       => $tax_mod,
            'qty'           => 1,
            'price'         => $price,
            'base_price'    => $base_price
        );
}

$total = $store->roundPrice($total);

echo('<pre>');
print_r($args);
//print_r($order->getData());
echo('
');$ grand_total = (float) $ order-> getData ('grand_total');// $ grand_total = $ store-> roundPrice ($ grand_total);echo ('

Мой итог :'. $ total. '

');echo ('

Итого :'. $ grand_total. '

');выход;
...