AI store generator for ecommerce, Malaysia first. Laravel 13 + React + TypeScript.
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183
  1. <?php
  2. namespace App\Commerce;
  3. use App\Models\Product;
  4. use App\Models\Store;
  5. use Illuminate\Contracts\Session\Session;
  6. use Illuminate\Support\Collection;
  7. /**
  8. * A shopper's cart for one store.
  9. *
  10. * It is kept in the browser session, so shoppers do not need an account, and each store
  11. * has its own cart. Only product ids and quantities are saved. Names, prices and stock are
  12. * always read fresh from the database, so the cart can never show an old price.
  13. */
  14. class Cart
  15. {
  16. /** The most of one product a shopper may put in the cart. */
  17. public const int MAX_QUANTITY = 99;
  18. /** True when a quantity was lowered or an item dropped while loading, because stock or status changed. */
  19. private bool $adjusted = false;
  20. public function __construct(
  21. private readonly Session $session,
  22. private readonly Store $store,
  23. ) {}
  24. /**
  25. * Put more of a product in the cart. Returns how many are in the cart afterwards.
  26. */
  27. public function add(Product $product, int $quantity): int
  28. {
  29. return $this->store(($this->quantities()[$product->id] ?? 0) + $quantity, $product);
  30. }
  31. /**
  32. * Set exactly how many of a product are in the cart. Zero removes it.
  33. * The number is capped by the stock and by MAX_QUANTITY.
  34. */
  35. public function set(Product $product, int $quantity): int
  36. {
  37. return $this->store($quantity, $product);
  38. }
  39. private function store(int $wanted, Product $product): int
  40. {
  41. $quantities = $this->quantities();
  42. $allowed = max(0, min($wanted, $product->stock, self::MAX_QUANTITY));
  43. if ($allowed === 0) {
  44. unset($quantities[$product->id]);
  45. } else {
  46. $quantities[$product->id] = $allowed;
  47. }
  48. $this->save($quantities);
  49. return $allowed;
  50. }
  51. public function remove(int $productId): void
  52. {
  53. $quantities = $this->quantities();
  54. unset($quantities[$productId]);
  55. $this->save($quantities);
  56. }
  57. public function clear(): void
  58. {
  59. $this->session->forget($this->key());
  60. }
  61. /**
  62. * The cart lines, with fresh product details.
  63. * Products that are no longer for sale are dropped, and quantities above the stock are lowered.
  64. *
  65. * @return Collection<int, array{product: Product, quantity: int, line_total: int}>
  66. */
  67. public function lines(): Collection
  68. {
  69. $quantities = $this->quantities();
  70. if ($quantities === []) {
  71. return collect();
  72. }
  73. $products = $this->store->products()
  74. ->active()
  75. ->with('images')
  76. ->whereKey(array_keys($quantities))
  77. ->get()
  78. ->keyBy('id');
  79. $kept = [];
  80. $lines = collect();
  81. foreach ($quantities as $productId => $quantity) {
  82. $product = $products->get($productId);
  83. $allowed = $product ? min($quantity, $product->stock, self::MAX_QUANTITY) : 0;
  84. if ($allowed !== $quantity) {
  85. $this->adjusted = true;
  86. }
  87. if ($product === null || $allowed < 1) {
  88. continue;
  89. }
  90. $kept[$productId] = $allowed;
  91. $lines->push([
  92. 'product' => $product,
  93. 'quantity' => $allowed,
  94. 'line_total' => $product->price * $allowed,
  95. ]);
  96. }
  97. if ($kept !== $quantities) {
  98. $this->save($kept);
  99. }
  100. return $lines;
  101. }
  102. /**
  103. * What the storefront is allowed to see. Money is in ringgit here.
  104. *
  105. * @return array{count: int, subtotal: float|int, adjusted: bool, lines: array<int, array<string, mixed>>}
  106. */
  107. public function toStorefront(): array
  108. {
  109. $lines = $this->lines();
  110. return [
  111. 'count' => (int) $lines->sum('quantity'),
  112. 'subtotal' => $lines->sum('line_total') / 100,
  113. 'adjusted' => $this->adjusted,
  114. 'lines' => $lines->map(fn (array $line) => [
  115. 'product' => $line['product']->toStorefront(),
  116. 'quantity' => $line['quantity'],
  117. 'max' => min($line['product']->stock, self::MAX_QUANTITY),
  118. 'line_total' => $line['line_total'] / 100,
  119. ])->values()->all(),
  120. ];
  121. }
  122. /**
  123. * @return array<int, int> Product id to quantity.
  124. */
  125. private function quantities(): array
  126. {
  127. $saved = $this->session->get($this->key(), []);
  128. if (! is_array($saved)) {
  129. return [];
  130. }
  131. $clean = [];
  132. foreach ($saved as $productId => $quantity) {
  133. if (is_int($productId) && is_int($quantity) && $quantity > 0) {
  134. $clean[$productId] = $quantity;
  135. }
  136. }
  137. return $clean;
  138. }
  139. /**
  140. * @param array<int, int> $quantities
  141. */
  142. private function save(array $quantities): void
  143. {
  144. $this->session->put($this->key(), $quantities);
  145. }
  146. private function key(): string
  147. {
  148. return 'cart.'.$this->store->id;
  149. }
  150. }