llp 1 неделя назад
Родитель
Сommit
cb530a7c89
1 измененных файлов с 28 добавлено и 0 удалено
  1. 28 0
      packages/Longyi/FreeGift/src/Services/GiftCartSummary.php

+ 28 - 0
packages/Longyi/FreeGift/src/Services/GiftCartSummary.php

@@ -64,6 +64,7 @@ class GiftCartSummary
 
         $allowedByRule = [];
         $reservedByRule = [];
+        $giftsByRule = [];
 
         foreach ($this->giftItemRepository->getByCart($cartId) as $row) {
             if ($row->allowed_qty < 1) {
@@ -126,11 +127,13 @@ class GiftCartSummary
             );
             $gift->allowed_qty = (float) $row->allowed_qty;
             $gift->reserved_qty = (float) $row->reserved_qty;
+            // 「一组合计送 N 个」的规则下面会按整组名额修正,这里先放逐行差值
             $gift->remaining_qty = max(0, (float) $row->allowed_qty - (float) $row->reserved_qty);
             $gift->cart_item_id = $row->cart_item_id ? (int) $row->cart_item_id : null;
             $gift->is_deleted = (bool) $row->is_item_deleted;
 
             $gifts[] = $gift;
+            $giftsByRule[$ruleId][] = $gift;
         }
 
         foreach ($groups as $ruleId => $group) {
@@ -143,6 +146,31 @@ class GiftCartSummary
 
             $group->reserved_qty = (float) ($reservedByRule[$ruleId] ?? 0);
             $group->remaining_qty = max(0, $group->allowed_qty - $group->reserved_qty);
+
+            /*
+             * 「一组合计送 N 个」:名额是整组共享的,逐候选的 remaining_qty 也必须
+             * 按组修正。否则名额已经被某个 SKU 用掉的组里,其余候选还会各自显示
+             * "可领 N 件",接口就变成「已送 1 件 + 还能领 1 件」,
+             * 前端展示出来就像送了 2 件。
+             *
+             * 已加购 / 被用户删掉的候选一律 0;剩下的名额按顺序分配给未加购的候选。
+             */
+            if ($group->type === Gift::TYPE_ONE) {
+                $remaining = $group->remaining_qty;
+
+                foreach ($giftsByRule[$ruleId] ?? [] as $gift) {
+                    if ($gift->reserved_qty > 0 || $gift->cart_item_id || $gift->is_deleted) {
+                        $gift->remaining_qty = 0;
+
+                        continue;
+                    }
+
+                    $take = min((float) $gift->allowed_qty, $remaining);
+
+                    $gift->remaining_qty = max(0, $take);
+                    $remaining -= $take;
+                }
+            }
         }
 
         return [array_values($groups), $gifts];