Magento – Check if coupon is valid for a quote

couponquotevalidation

I need to programitcally re order an Item.

I have achieved this by

  1. Cancel the current order
  2. Get the cancelled order quote
  3. Ammend the Qtys
  4. Recalulate the shipping

This is all fine… now I need to calculate if any coupons were applied are now still valid for the new order? Forinstance a rule would be that a coupon is only valid if an order is over £10.00 – I re order from the old quote but now my order is only £9.00 which means the coupon is not valid.

How can I check whether the coupon that is assigned to the quote is now valid for the new order totals?

Thanks in advance..

Best Answer

The following answer is just theoretical. I haven't tested it, but it seams the way to go.
You can get the cart rules that were applied to the order you cancel like this:

$ruleIds = explode(',', $order->getAppliedRuleIds());

Then you need to get the rules applied:

$rules = Mage::getModel('salesrule/rule')->getCollection()
       ->addFieldToFilter('rule_id', array('in'=>$ruleIds));

Then loop through the rules and try to apply the coupons to the quote.

foreach ($rules as $rule){
    if (!$rule->getCode()) {//skip rules without codes
        continue;
    }
    //normaly there should be only one rule that gets here since you can apply only one coupon code
    $quote->setCouponCode($rule->getCode())->collectTotals()->save(); 
    $quoteCouponCode = $quote->getCouponCode();//get the applied coupon code from the quote
    if ($quoteCouponCode){
        //$rule is valid and $rule->getCode() is a valid coupon code
    }
    //remove the coupon code from the quote if you want
    $quote->setCouponCode('')->collectTotals()->save(); 
}

There is a chance that even for a valid coupon you will get the 'not valid' result. This may happen if you just reached the coupon usage limit (per customer or total) or if you reorder after the expiration date of the rule.