| 1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950 |
- <?php
-
- namespace App\Commerce;
-
- use App\Models\BundleItem;
- use App\Models\Product;
-
- /**
- * A bundle has no stock of its own. It can be sold as many times as the items inside it allow:
- * a bundle of 2 sambal and 1 kerepek, with 10 sambal and 3 kerepek left, has 3 left (10 ÷ 2 = 5, 3 ÷ 1 = 3).
- *
- * The answer is saved on the bundle's own stock column, so lists, cards and the cart read it like any
- * other product. Call refresh() whenever stock in the store changes.
- */
- class BundleStock
- {
- /**
- * Work out the stock of every bundle in one store again.
- */
- public static function refresh(int $storeId): void
- {
- Product::query()
- ->where('store_id', $storeId)
- ->where('is_bundle', true)
- ->with(['bundleItems.product', 'bundleItems.variant'])
- ->get()
- ->each(function (Product $bundle): void {
- $stock = self::for($bundle);
-
- if ($bundle->stock !== $stock) {
- $bundle->stock = $stock;
- $bundle->saveQuietly();
- }
- });
- }
-
- /**
- * How many of this bundle can be sold now.
- */
- public static function for(Product $bundle): int
- {
- if ($bundle->bundleItems->isEmpty()) {
- return 0;
- }
-
- return (int) $bundle->bundleItems
- ->map(fn (BundleItem $item) => intdiv(max(0, $item->stock()), max(1, $item->quantity)))
- ->min();
- }
- }
|