0

I need to create orders in Magento from XML source, the Order is placed fine in magento but the cart rules don't apply correctly. The cart rules don't apply the discount in each article. If I check rules applied in each item I could see that the Id rule is applied to the item but the discount dont appears.

If I make the same order manually using magento admin the cart rules applies perfectly.

The code process all .xml files in a directory and move them to a processed directory.

require_once '../../app/Mage.php';
Mage::app();

ini_set('xdebug.var_display_max_depth', 10);
ini_set('xdebug.var_display_max_children', 256);
ini_set('xdebug.var_display_max_data', 1024);


//$archivos  = scandir('D:\FTP\COM\XMLPendientes');
$archivos  = array_diff(scandir('D:\FTP\COM\XMLPendientes'), array('..', '.'));

foreach($archivos as $archivo)
{
    echo '<p>****** '.date("Ymd-His").' Procesando '.$archivo.' *****';
    $ProcesadoOk = ProcesarXML('D:\FTP\COM\XMLPendientes\\'.$archivo);
    echo '<br>Procesado D:\FTP\COM\XMLPendientes\\'.$archivo.' Pedido '.$ProcesadoOk;
    rename('D:\FTP\COM\XMLPendientes\\'.$archivo, 'D:\FTP\COM\XMLEnviados\\'.$archivo);
    echo '<br>Movido D:\FTP\COM\XMLPendientes\\'.$archivo, ' --> D:\FTP\COM\XMLEnviados\\'.$archivo;
}

$fp = fopen("registro.html", "a");
$data = ob_get_contents();
//$data = ob_get_clean();
fwrite($fp, $data);
fclose($fp); 

//$ProcesadoOk = ProcesarXML('D:\FTP\COM\XMLPendientes\003089-07092015155055.xml');

function ProcesarXML($archivo)
{ 
    $pedido = simplexml_load_file($archivo);
    //var_dump($archivo);
    // Obtener ID cliente
    //$query = "000071X";
    //var_dump($pedido);
    $query = $pedido->Cliente[0]->Codigo;
    echo '<br>Asociado Cod Ccp: '.$query;
    $model = Mage::getSingleton('customer/customer');
    $result = $model->getCollection()
            ->addAttributeToSelect('*')
            ->addAttributeToFilter('codigo_ccp', array('like' => "%$query%"))
            ->addAttributeToFilter('website_id', array('like' => "1"));
    foreach($result as $r) 
    {       
            $customer = $model->load($r->getId());
            echo '<br>Nombre: '.$customer->getFirstname().' Nombre 2: '.$customer->getLastname();
            $customerId = $customer->getId();
            echo '<br>Asociado Magento ID: '.$customerId;
    }
    // FIN Obtener ID cliente


    $quote = Mage::getModel('sales/quote')->setStoreId(Mage::app()->getStore('default')->getId());

    // for customer orders:
    $customer = Mage::getModel('customer/customer')->setWebsiteId(1)->load($customerId);
    $quote->assignCustomer($customer);



    // add product(s)
    //$product = Mage::getModel('catalog/product')->load(140268);

    foreach ($pedido->Detalle[0]->Articulo as $item)
    {
        if ($item->Qty != '0') {
            //$sku = $item->Sku;
            //$product = Mage::getModel('catalog/product')->loadByAttribute('sku', $sku);
            //$product = Mage::getModel('catalog/product')->load($product->getId());

            $product = Mage::getModel('catalog/product')->load($item->Id);
            echo '******************************PRODUCTO********************';
            var_dump($product);

            $buyInfo = array(
                    'qty' => (string)$item->Qty,
                    //añado (string) por error Uncaught exception 'Exception' with message 'Serialization of 'SimpleXMLElement' is not allowed'
                    // custom option id => value id
                    // or
                    // configurable attribute id => value id
            );
            echo '<br>ID: '.$product->getId().' Sku: '.$item->Sku.' Qty: '.$item->Qty;
            $quote->addProduct($product, new Varien_Object($buyInfo));
        }
    }

    $addressData = array(
            'firstname' => $customer->getFirstname(),
            'lastname' => $customer->getLastname(),
            'street' => $pedido->ID,
            'city' => 'Ciudad',
            'postcode' => '123456',
            'telephone' => '123456',
            'country_id' => 'ES',
            'region_id' => 12, // id de la tabla directory_country_region
    );

    $billingAddress = $quote->getBillingAddress()->addData($addressData);
    $shippingAddress = $quote->getShippingAddress()->addData($addressData);

    $shippingAddress->setCollectShippingRates(true)->collectShippingRates()
                    ->setShippingMethod('flatrate_flatrate')
                    ->setPaymentMethod('banktransfer');


    $quote->getPayment()->importData(array('method' => 'banktransfer'));

    $quote->pedido_comercial = 'ProcesadoCOM';
    $quote->pedido_usuario = 'ComercialX'; 

    echo '******************************QUOTE BEFORE COLLECTTOTALS********************';
    var_dump($quote);
    $quote->collectTotals()->save(); 
    echo '******************************QUOTE AFTHER COLLECTTOTALS********************';
    var_dump($quote);

    // $quote->setTotalsCollectedFlag(false)->collectTotals()->save(); //ERROR no vale

    //Probando esto: No funciona
    //$convertQuote = Mage::getSingleton('sales/convert_quote'); 
    //$order = $convertQuote->toOrder($quote); 

    $service = Mage::getModel('sales/service_quote', $quote);
    $service->submitAll();
    echo '******************************SERVICE****************************************';
    var_dump($service);
    $order = $service->getOrder();
    echo '******************************ORDER****************************************';
    var_dump($order);

    $order = $order->setPedidoComercial("ProcesadoCOM");
    $order = $order->setPedidoUsuario("ComercialX");
    $order->addStatusHistoryComment($pedido->Observaciones);
    $order->addStatusHistoryComment('COM '.$pedido->ID);
    //$order->addStatusHistoryComment('Pedido de Prueba. NO PROCESAR');

    //Pruebas reglas carrito
    //$order->collectTotals()->save(); //ERROR no vale
    //Fin Pruebas reglas carrito

    $order->save();

    //printf("Creado pedido %s\n", $order->getIncrementId());

    return $order->getIncrementId();
}

Check this order screen capture:

magento cart screen

The i simbol show me what rules are applied in each item, you could see that in the item MAW1280590 I have:

SFS Weekend Allweek rule applied, it must give 10% discount on item whit SKU beginning with MAW. Dont apply the discount but appears in the rules applied on item.

Ti22 12+2 PLV rule applied, this rule add a free gift for all items with SKU begining with MTI. This item dont match the rule but is being applied.

The cart rules is applied using category of items to check if must be applicable.

When I create order in magento/admin sometimes I have to click on "Update Items and Qty's" to see all the rules apllied correctly. Is there any way to process "Update Items and Qty's" programatically?.

Any idea? Thanks!!

Added:

I try some code modifications but no luck....

//Prueba ME DEJA TODO EL PEDIDO A CERO. ERROR ALL PRICES TO ZERO
    /*
    $items = $quote->getAllVisibleItems();
    foreach($items as $item)
    {
        $item->setCustomPrice(0);
        $item->setOriginalCustomPrice(0);
        $item->getProduct()->setIsSuperMode(true);
        $item->save();
    }
    $quote->save();
    $quote->setTotalsCollectedFlag(false)->collectTotals();
    */
    //Fin Prueba

    //Prueba 2 IGUAL, NO APLICA LOS DESCUENTOS. ERROR, DONT APPLY DISCOUNTS.
    /*
    $quote->setTotalsCollectedFlag(false);
    $quote->getShippingAddress()->unsetData('cached_items_all');
    $quote->getShippingAddress()->unsetData('cached_items_nominal');
    $quote->getShippingAddress()->unsetData('cached_items_nonnominal');
    $quote->collectTotals();
    */
    //Fin Prueba 2

    //Prueba 3 IGUAL, NO APLICA LOS DESCUENTOS. ERROR, DONT APPLY DISCOUNTS.
    //$cart = Mage::getSingleton('checkout/session')->getQuote();
    /*
    foreach ($quote->getAllAddresses() as $address)
    {
        $address->unsetData('cached_items_nonnominal');
        $address->unsetData('cached_items_nominal');
    }
    $quote->setTotalsCollectedFlag(false);
    $quote->collectTotals();
    */
    //Fin Prueba 3

Help please!! :)

New info:

Testing rules we discover that only fails on rules made by Amasty Special Promotion Pro module, from Magento Connect. We are contacting with Amasty to get help.

1
  • For the moment I change my cart rules to standard magento cart rules avoiding use Amasty module cart rules, and it works. Still waiting to Amasty support. – jfrubio Oct 28 '15 at 10:59
0

No way. Imposible to make it works right with Amasty Special Promotion Pro module.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.