I want to add custom discount to the quote programmatically but the total not updated and when place the order the discount is not affected.
$cartId = 199;
$quote = $this->cartRepositoryInterface->get($cartId); // load empty cart quote
$discount = 10; // in percent
$quoteSubTotal = $quote->getSubtotal();
$quoteBaseSubTotal = $quote->getBaseSubtotal();
foreach ($quote->getAllVisibleItems() as $item) {
$quoteItem = $quote->getItemById($item->getId());
if($discount != 0) {
$discountAmount = (float) (($quoteItem->getPrice()*$quoteItem->getQty())*$discount)/100;
}
$finalDiscount += $discountAmount;
$item->setDiscountAmount($discountAmount);
$item->setBaseDiscountAmount($discountAmount);
$item->getProduct()->setIsSuperMode(true);
$item->calcRowTotal();
$item->save();
}
if($finalDiscount > 0) {
$quote->setSubtotalWithDiscount($quoteSubTotal - $finalDiscount);
$quote->setBaseSubtotalWithDiscount($quoteBaseSubTotal - $finalDiscount);
$quote->setGrandTotal($quoteSubTotal - $finalDiscount);
$quote->setBaseGrandTotal($quoteBaseSubTotal - $finalDiscount);
$quote->collectTotals();
$quote->collectTotals()->save();
}
But It's not Working, Any suggestion please?