AI store generator for ecommerce, Malaysia first. Laravel 13 + React + TypeScript.
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. <?php
  2. namespace App\Commerce;
  3. use App\Models\BundleItem;
  4. use App\Models\Product;
  5. /**
  6. * A bundle has no stock of its own. It can be sold as many times as the items inside it allow:
  7. * a bundle of 2 sambal and 1 kerepek, with 10 sambal and 3 kerepek left, has 3 left (10 ÷ 2 = 5, 3 ÷ 1 = 3).
  8. *
  9. * The answer is saved on the bundle's own stock column, so lists, cards and the cart read it like any
  10. * other product. Call refresh() whenever stock in the store changes.
  11. */
  12. class BundleStock
  13. {
  14. /**
  15. * Work out the stock of every bundle in one store again.
  16. */
  17. public static function refresh(int $storeId): void
  18. {
  19. Product::query()
  20. ->where('store_id', $storeId)
  21. ->where('is_bundle', true)
  22. ->with(['bundleItems.product', 'bundleItems.variant'])
  23. ->get()
  24. ->each(function (Product $bundle): void {
  25. $stock = self::for($bundle);
  26. if ($bundle->stock !== $stock) {
  27. $bundle->stock = $stock;
  28. $bundle->saveQuietly();
  29. }
  30. });
  31. }
  32. /**
  33. * How many of this bundle can be sold now.
  34. */
  35. public static function for(Product $bundle): int
  36. {
  37. if ($bundle->bundleItems->isEmpty()) {
  38. return 0;
  39. }
  40. return (int) $bundle->bundleItems
  41. ->map(fn (BundleItem $item) => intdiv(max(0, $item->stock()), max(1, $item->quantity)))
  42. ->min();
  43. }
  44. }