Add coupon to order programmatically with modified coupon code

I've modified the coupon validation function to check for grouped SKUs as well as the simple SKU. It works great on the Magento front end, but I have a process that creates an order programmatically, and I'm not able to get the coupon to work there. I've traced it down to the fact that since the programmatic order doesn't use the checkout/cart, it can't get the parent item.

Here's the validate function inside of local/Mage/Rule/Model/Condition/Abstract.php:

public function validate(Varien_Object $object)
{
    $parentCode = '';
    if($this->getAttribute() == 'sku'){
        $quote = Mage::getSingleton('checkout/cart')->getQuote();
        if($qItem = $quote->getItemByProduct($object)){
            if($parent = $qItem->getParentItem()){
                $parentCode = $parent->getSku();
            }
            else if($buyRequest = $qItem->getOptionByCode('info_buyRequest'))
            {
                $options = unserialize($buyRequest->getValue());
                if(!empty($options['super_product_config']))
                {
                    $prodID = $options['super_product_config']['product_id'];
                    $parentCode = Mage::getModel('catalog/product')->load($prodID)->getSku();
                }
            }
        }
    }
    return ($this->validateAttribute($object->getData($this->getAttribute())) || $this->validateAttribute($parentCode)) ? true : false;
}

And the relevant parts of my order creation:

function createQuote(){
    $quote = Mage::getModel('sales/quote');
    if (!$quote) {
        Mage::log("Error in quote! ".$parentId);
        return;
    }
    $this->quote = $quote;
}

function setCoupon($coupon){
    if(!empty($coupon))
        $this->_coupon = $coupon;
}

function setQuoteAddress(){
    $quote = $this->quote;
    $shippingAddress = new Mage_Sales_Model_Quote_Address;
    $billingAddress = new Mage_Sales_Model_Quote_Address;
    $billingAddress->setData($this->_billingAddr);
    $shippingAddress->setData($this->_shippingAddr);
    $quote->setBillingAddress($billingAddress);
    $quote->setShippingAddress($shippingAddress);
    $quote->getShippingAddress()->setSameAsBilling($this->_sameAsBilling);
    $quote->getBillingAddress()->setEmail($this->_billingAddr['email']);

    if(!empty($this->_coupon)){
        $quote->setCouponCode($this->_coupon);
    }
}

function setAddress($request){

    // Address validation here
    $this->setQuoteAddress();

    return false;   
}

Edit It could possibly be because I wasn't adding the items to the cart, like I had thought, but when I try, the total is 0:

// Total is correct, cannot pull the ItemByProduct/getParentItem
$cart = Mage::getModel('checkout/cart');
if(!$quote->hasProductId($parentId)){
    $quote->addProduct($product, new Varien_Object($params));
//  $quote->collectTotals()->save();
    Mage::getSingleton('checkout/session')->setCartWasUpdated(true);
}

// Amount is 0
$cart = Mage::getModel('checkout/cart');
$cart->init();
//Add product to cart with specified parameters and save the cart object
if(!$quote->hasProductId($parentId)){
    $cart->addProduct($product, new Varien_Object($params));
    $cart->save();
    //  $quote->collectTotals()->save();
    Mage::getSingleton('checkout/session')->setCartWasUpdated(true);
}

Solutions

Oddly, I fixed it by adding it to both the cart and the quote:

$cart = Mage::getModel('checkout/cart');
//Add product to cart with specified parameters and save the cart object
if(!$quote->hasProductId($parentId)){
    $cart->addProduct($product, new Varien_Object($params))->save();
    $quote->addProduct($product, new Varien_Object($params))->save();
    Mage::getSingleton('checkout/session')->setCartWasUpdated(true);
}

I'm not sure if this will cause issues, but I'm going to do a bit more testing.

Similar questions

Magento tells me to apply modified catalog price rules but there are no rules at all
I noticed a message in Promotions -> Catalog Price Rules: "There are rules that have been changed but were not applied. Please, click Apply Rules in order to see immediate effect in the catalog." But I couldn't see any rule at all. Not in backend, not in database. All these tables were empty: I cleared cache and ran a full reindex but the messag...
Copyright notice on modified base/default template in own design package
When creating a custom design package for a client I often find myself copying a template from either base/default or rwd/default and modifying this template to the client's needs. The license used is the Academic Free License (AFL 3.0) (http://opensource.org/licenses/afl-3.0.php) This states the following: 6) Attribution Rights. You must retain, i...
Which file should be modified/created to enable OPcache?
Magento strongly recommends PHP OPcache is enabled for performance reasons. PHP 5.6 with Zend OPcache is installed on my server but i dont know which file should be modified to enable OPcache features.
magento 2 - best practice to modified database structure
What is the best practice to extend / modified structure database? Let say we want to add some field in customer_entity table, is it violate the rules, or we have to add new table? I didn't find any guide documentation about it.
Modified Price.php to use cost*markup but category page shows old price field value
I have just modified the getPrice function in app/code/core/Mage/Catalog/Model/Product/Type/Price.php to: However in my category pages the price displayed is still the old price as entered in the Price attribute in the admin section. Could someone please help me work out what I need to edit to get both prices displaying the same value again please?...
Modified product collection: Products on category do not match number of results
I need to modify the product collection on category page. Therefore, I've modified the _getProductCollection() in Mage/Catalog/Block/Product/List.php and added an additional filter $this->_productCollection->addAttributeToFilter('entity_id', $prods); But this works only partly. The product count in the top bar shows the correct product count ...

Also ask

We use cookies to deliver the best possible experience on our website. By continuing to use this site, accepting or closing this box, you consent to our use of cookies. To learn more, visit our privacy policy.