Is there someway to find all the coupon codes which is applicable for the logged in customer?
One way is to collect all the coupon codes, loop over them and apply to quote object in order to check it's validity.
Something similar to following code:
$eligibleCoupons = array();
$allAvailableCoupons = array('xxx', 'yyy', 'zzz', /* ... */);
foreach ($allAvailableCoupons as $couponCode) {
$codeLength = strlen($couponCode);
$isCodeLengthValid = $codeLength && $codeLength <= Mage_Checkout_Helper_Cart::COUPON_CODE_MAX_LENGTH;
$this->_getQuote()->getShippingAddress()->setCollectShippingRates(true);
$this->_getQuote()->setCouponCode($isCodeLengthValid ? $couponCode : '')
->collectTotals()
->save();
if ($codeLength) {
if ($isCodeLengthValid && $couponCode == $this->_getQuote()->getCouponCode()) {
$eligibleCoupons[] = $couponCode
//finally remove coupon code apply
$this->_getQuote()->setCouponCode('')
->collectTotals()
->save();
} else {
}
}
}
var_dump($eligibleCoupons);
But this method seems lengthy and resource consuming.
I bet there must be an easier approach for this.
Best Answer
The coupon codes and shopping cart rules in general (even if they don't have a coupon code) have meaning relative to a cart (quote) object. They ca depend on different qtys in the cart, they can depend on shipping and billing addresses, or even on shipping and payment methods.
So you have to involve a quote in the process of validating a rule.
Magento has something for getting the valid rules depending on a quote and a coupon code.
See
Mage_SalesRule_Model_Validator::init
.Inside that method there is this code that (I think) it filters the valid rules depending on the coupon code, website id and customer group.
The code that actually retrieves these rules is located in
Mage_SalesRule_Model_Resource_Rule_Collection::setValidationFilter
.This method receives 4 parameters.
So my idea is to build your own method that is similar to the
setValidationFilter
but remove from that the conditions for the coupon codes.You will end up with a set of rules that can be valid if you have the proper coupon code.
Then just loop through the rules you get and check which ones have coupon codes.
Those are the coupon codes you are looking for.
[EDIT]
Fogot one thing. The method I mentioned does not involve a quote. It just filters a bit the rules. You will still have to apply the coupons to a quote and see if they are valid, but at least you eliminate some of the rules.