I want to retrieve multiple coupon data via the REST API. I am using it with and without a coupon
This is my code
$subtotal = $totals->getSubTotal();
$couponDetails = [];
if ($quote->getAppliedRuleIds()) {
// Get applied rules
$ruleIds = explode(',', $quote->getAppliedRuleIds());
$ruleIds = array_filter(array_map('trim', $ruleIds));
if (!empty($ruleIds)) {
$collection = $this->ruleCollectionFactory->create();
$collection->addFieldToFilter('rule_id', ['in' => $ruleIds]);
foreach ($collection as $rule) {
/** @var VendorModuleModelDataCouponDetail $detail */
$detail = $this->couponDetailFactory->create();
$detail->setAppliedRuleId($rule->getId());
$detail->setCouponCode($rule->getCode() ?? '');
$detail->setCouponTitle($rule->getName());
$detail->setCouponDescription($rule->getDescription());
$detail->setCouponActionType($rule->getSimpleAction());
$discountValue = 0;
switch ($rule->getSimpleAction()) {
case 'by_percent':
$discountPercent = $rule->getDiscountAmount();
$discountValue = $subtotal * ($discountPercent / 100);
break;
case 'by_fixed':
$discountPerItem = $rule->getDiscountAmount();
// Get total qty from quote items (filter by conditions if needed)
$totalQty = 0;
foreach ($quote->getAllVisibleItems() as $item) {
$appliedRuleIds = explode(',', (string)$item->getAppliedRuleIds());
if (in_array($rule->getId(), $appliedRuleIds)) {
$totalQty += $item->getQty();
}
}
$discountValue = $discountPerItem * $totalQty;
break;
case 'cart_fixed':
$discountValue = $rule->getDiscountAmount();
break;
default:
$discountValue = 0;
}
$detail->setCouponValue(round($discountValue, 2));
// Subtract discount for sequential rules
$subtotal -= $discountValue;
$couponDetails[] = $detail;
}
}
}
//end
$extensionAttributes->setCouponDetails($couponDetails);
OUTPUT
"extension_attributes": {
"coupon_details": [
{
"applied_rule_id": "445",
"coupon_code": "Devi1",
"coupon_title": "devi1 with 1111",
"coupon_description": "devi1 with 1111",
"coupon_value": 418.95,
"coupon_action_type": "by_percent"
},
{
"applied_rule_id": "448",
"coupon_code": "",
"coupon_title": "Access Plus - Tier 2",
"coupon_description": "Discount configuration",
"coupon_value": 291.55,
"coupon_action_type": "by_percent"
}
]
}
}
The issue is when the rule configures different types, my code does not work. Please give me any other solution to achieve this