1

I have a quick question on magento coupon code generator. Please see the below method in core/Mage/SalesRule/Model/Rule.php:

 /**
 * Acquire coupon instance
 *
 * @param bool $saveNewlyCreated Whether or not to save newly created coupon
 * @param int $saveAttemptCount Number of attempts to save newly created coupon
 *
 * @return Mage_SalesRule_Model_Coupon|null
 */
public function acquireCoupon($saveNewlyCreated = true, $saveAttemptCount = 10)
{
    if ($this->getCouponType() == self::COUPON_TYPE_NO_COUPON) {
        return null;
    }
    if ($this->getCouponType() == self::COUPON_TYPE_SPECIFIC) {
        return $this->getPrimaryCoupon();
    }
    /** @var Mage_SalesRule_Model_Coupon $coupon */
    $coupon = Mage::getModel('salesrule/coupon');
    $coupon->setRule($this)
        ->setIsPrimary(false)
        ->setUsageLimit($this->getUsesPerCoupon() ? $this->getUsesPerCoupon() : null)
        ->setUsagePerCustomer($this->getUsesPerCustomer() ? $this->getUsesPerCustomer() : null)
        ->setExpirationDate($this->getToDate());

    $couponCode = self::getCouponCodeGenerator()->generateCode();
    $coupon->setCode($couponCode);

    $ok = false;
    if (!$saveNewlyCreated) {
        $ok = true;
    } else if ($this->getId()) {
        for ($attemptNum = 0; $attemptNum < $saveAttemptCount; $attemptNum++) {
            try {
                $coupon->save();
            } catch (Exception $e) {
                if ($e instanceof Mage_Core_Exception || $coupon->getId()) {
                    die(print_r($e));
                    throw $e;
                }
                $coupon->setCode(
                    $couponCode .
                    self::getCouponCodeGenerator()->getDelimiter() .
                    sprintf('%04u', rand(0, 9999))
                );
                continue;
            }
            $ok = true;
            break;
        }
    }
    if (!$ok) {
        Mage::throwException(Mage::helper('salesrule')->__('Can\'t acquire coupon.'));
    }

    return $coupon;
}

I can see it has 10 attempts by default. However if I generate a code which exists in the database, I get an exception immediately:

a:5:{i:0;s:41:"Coupon with the same code already exists.";i:1;s:3513:"#0 /var/www/html/magento1/app/code/core/Mage/Core/Model/Resource/Db/Abstract.php(676)

Is there any way to prevent this without touching the core code? And in case the coupon code exists - should there not be another try as there are 10 attempts?

  • That's an interesting question. Do you use that method in a custom module ? Because that acquireCoupon method is not used anywhere in Magento CE codebase – Raphael at Digital Pianism Oct 25 '16 at 14:18
  • Hello, yes I am using acquireCoupon method in my custom extension. So far it does look like there is no way around it. – user3713377 Oct 25 '16 at 15:55
  • Are you on Enterprise ? – Raphael at Digital Pianism Oct 25 '16 at 17:39
1

I think you should not use that acquireCoupon method. Indeed, this method is not used anywhere in Magento CE core code but it's used in EE and I'm afraid it might be an old / unremoved / buggy method. I would be very interested to see why it's here.

If you want to use the mass coupon generator, here is how you should do it:

// Load your salesrule
$rule = Mage::getModel('salesrule/rule')->load($ruleId);
// Get the coupon mass generator
$generator = $rule->getCouponMassGenerator();
// Set the generator data
$data = array(
    'qty' => 1, //number of coupons to generate
    'length' => 10, //length of coupon string
    'prefix' => "test_",
    'format' => Mage_SalesRule_Helper_Coupon::COUPON_FORMAT_ALPHANUMERIC,
    'rule_id' => $ruleId //the id of the rule you will use as a template
);
// Validate the data
if ($generator->validateData($data)) {
    $generator->setData($data);
    $generator->generatePool();
    $generatedCount = $generator->getGeneratedCount();
}

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.