Skip to main content
3 of 5
Fixed grammer
Piyush
  • 5.9k
  • 9
  • 34
  • 66

Magento 1 Restore coupon for a especific customer

I'm trying to restore a coupon for a specific customer, I know their id and the coupon code.

My code is:

$customerId = 98080;

$coupon = Mage::getModel('salesrule/coupon')->load('test-it', 'code');
$coupon->setTimesUsed($coupon->getTimesUsed()-1);

$coupon->save();             

$timesUsed = $coupon->getTimesUsed();

$write = Mage::getSingleton('core/resource')->getConnection('core_write');
$query = "UPDATE salesrule_coupon_usage SET times_used = times_used-1 WHERE customer_id='".$customerId."' AND coupon_id='".$coupon->getId()."'";

$result = $write->query($query);
 
if ($customerCoupon = Mage::getModel('salesrule/rule_customer')->loadByCustomerRule($customerId, $coupon->getRuleId())) {
    $customerCoupon->setTimesUsed($customerCoupon->getTimesUsed()-1);

    $customerCoupon->save();
}

And apparently all is working fine, I check the customer in the database and he doesn't have the discount assigned:

SELECT group_concat(distinct sfo.coupon_code) FROM sales_flat_order sfo
WHERE coupon_code IS NOT NULL
AND customer_email='[email protected]'
GROUP BY customer_email;
// group_concat(distinct sfo.coupon_code) == 0,one-discount,another

And in the code table:

SELECT coupon_code, count(coupon_code) FROM sales_flat_order
WHERE coupon_code ='test-it4'
GROUP BY coupon_code;
//Empty set

At first, all goes well, I can use the code again, but in the last step of the checkout I have the next message:

There was an error processing your order. Please contact us or try again later.

I don't know why the logs don't show anything