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');


$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())) {


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@example.com'
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


I have this error in apache2 log:

Integrity constraint violation: 1062 Duplicate entry '331536-98080' for key 'PRIMARY''

Where 331536 is the coupon_id and 98080 is the customer_id, but I don't find in which table is this data stored


I need to execute:

$query = "DELETE FROM salesrule_coupon_usage WHERE coupon_id='".$ruleId."' AND customer_id='".$customerId."';";

And all works again

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.