cancel
Showing results for 
Search instead for 
Did you mean: 

Magento 1 Restore coupon for a especific customer

SOLVED

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@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

1 ACCEPTED SOLUTION

Accepted Solutions

Re: Magento 1 Restore coupon for a especific customer

I only need to execute:

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

 

And all works again

View solution in original post

2 REPLIES 2

Re: Magento 1 Restore coupon for a especific customer

UPDATE

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

Re: Magento 1 Restore coupon for a especific customer

I only need to execute:

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

 

And all works again