AI store generator for ecommerce, Malaysia first. Laravel 13 + React + TypeScript.
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

Cart.php 8.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269
  1. <?php
  2. namespace App\Commerce;
  3. use App\Models\DiscountCode;
  4. use App\Models\Product;
  5. use App\Models\Store;
  6. use App\Storefront\StorefrontText;
  7. use Illuminate\Contracts\Session\Session;
  8. use Illuminate\Support\Collection;
  9. /**
  10. * A shopper's cart for one store.
  11. *
  12. * It is kept in the browser session, so shoppers do not need an account, and each store
  13. * has its own cart. Only product ids and quantities are saved. Names, prices and stock are
  14. * always read fresh from the database, so the cart can never show an old price.
  15. */
  16. class Cart
  17. {
  18. /** The most of one product a shopper may put in the cart. */
  19. public const int MAX_QUANTITY = 99;
  20. /** True when a quantity was lowered or an item dropped while loading, because stock or status changed. */
  21. private bool $adjusted = false;
  22. /** True when the discount code was taken out because it can no longer be used. */
  23. private bool $discountRemoved = false;
  24. public function __construct(
  25. private readonly Session $session,
  26. private readonly Store $store,
  27. ) {}
  28. /**
  29. * Put more of a product in the cart. Returns how many are in the cart afterwards.
  30. */
  31. public function add(Product $product, int $quantity): int
  32. {
  33. return $this->store(($this->quantities()[$product->id] ?? 0) + $quantity, $product);
  34. }
  35. /**
  36. * Set exactly how many of a product are in the cart. Zero removes it.
  37. * The number is capped by the stock and by MAX_QUANTITY.
  38. */
  39. public function set(Product $product, int $quantity): int
  40. {
  41. return $this->store($quantity, $product);
  42. }
  43. private function store(int $wanted, Product $product): int
  44. {
  45. $quantities = $this->quantities();
  46. $allowed = max(0, min($wanted, $product->stock, self::MAX_QUANTITY));
  47. if ($allowed === 0) {
  48. unset($quantities[$product->id]);
  49. } else {
  50. $quantities[$product->id] = $allowed;
  51. }
  52. $this->save($quantities);
  53. return $allowed;
  54. }
  55. public function remove(int $productId): void
  56. {
  57. $quantities = $this->quantities();
  58. unset($quantities[$productId]);
  59. $this->save($quantities);
  60. }
  61. public function clear(): void
  62. {
  63. $this->session->forget($this->key());
  64. $this->session->forget($this->discountKey());
  65. }
  66. /**
  67. * Put a discount code in the cart. Returns the problem (a StorefrontText key) when the code
  68. * does not exist or cannot be used at all; a code that only needs a bigger cart is kept.
  69. */
  70. public function applyCode(string $code): ?string
  71. {
  72. $discount = $this->store->discountCodes()->where('code', DiscountCode::normalize($code))->first();
  73. if ($discount === null) {
  74. return 'discount_invalid';
  75. }
  76. $problem = $discount->problemFor((int) $this->lines()->sum('line_total'));
  77. if ($problem !== null && $problem !== 'discount_minimum') {
  78. return $problem;
  79. }
  80. $this->session->put($this->discountKey(), $discount->code);
  81. return null;
  82. }
  83. /**
  84. * True when the last discount() call took the code out because it can no longer be used.
  85. */
  86. public function discountWasRemoved(): bool
  87. {
  88. return $this->discountRemoved;
  89. }
  90. public function removeCode(): void
  91. {
  92. $this->session->forget($this->discountKey());
  93. }
  94. /**
  95. * The code in the cart and what it is worth for these products.
  96. * A code that was deleted, switched off, expired or used up is taken out, and the cart says so once.
  97. */
  98. public function discount(int $subtotal): ?AppliedDiscount
  99. {
  100. $code = $this->session->get($this->discountKey());
  101. if (! is_string($code)) {
  102. return null;
  103. }
  104. $discount = $this->store->discountCodes()->where('code', $code)->first();
  105. $problem = $discount?->problemFor($subtotal);
  106. if ($discount === null || ($problem !== null && $problem !== 'discount_minimum')) {
  107. $this->removeCode();
  108. $this->discountRemoved = true;
  109. return null;
  110. }
  111. return new AppliedDiscount($discount, $problem === null ? $discount->amountFor($subtotal) : 0, $problem);
  112. }
  113. /**
  114. * The cart lines, with fresh product details.
  115. * Products that are no longer for sale are dropped, and quantities above the stock are lowered.
  116. *
  117. * @return Collection<int, array{product: Product, quantity: int, line_total: int}>
  118. */
  119. public function lines(): Collection
  120. {
  121. $quantities = $this->quantities();
  122. if ($quantities === []) {
  123. return collect();
  124. }
  125. $products = $this->store->products()
  126. ->active()
  127. ->with('images')
  128. ->whereKey(array_keys($quantities))
  129. ->get()
  130. ->keyBy('id');
  131. $kept = [];
  132. $lines = collect();
  133. foreach ($quantities as $productId => $quantity) {
  134. $product = $products->get($productId);
  135. $allowed = $product ? min($quantity, $product->stock, self::MAX_QUANTITY) : 0;
  136. if ($allowed !== $quantity) {
  137. $this->adjusted = true;
  138. }
  139. if ($product === null || $allowed < 1) {
  140. continue;
  141. }
  142. $kept[$productId] = $allowed;
  143. $lines->push([
  144. 'product' => $product,
  145. 'quantity' => $allowed,
  146. 'line_total' => $product->price * $allowed,
  147. ]);
  148. }
  149. if ($kept !== $quantities) {
  150. $this->save($kept);
  151. }
  152. return $lines;
  153. }
  154. /**
  155. * What the storefront is allowed to see. Money is in ringgit here.
  156. *
  157. * @return array{count: int, subtotal: float|int, discount: array<string, mixed>|null, total: float|int, adjusted: bool, lines: array<int, array<string, mixed>>}
  158. */
  159. public function toStorefront(): array
  160. {
  161. $lines = $this->lines();
  162. $subtotal = (int) $lines->sum('line_total');
  163. $discount = $lines->isEmpty() ? null : $this->discount($subtotal);
  164. $language = $this->store->language->value;
  165. return [
  166. 'count' => (int) $lines->sum('quantity'),
  167. 'subtotal' => $subtotal / 100,
  168. 'discount' => $discount === null ? null : [
  169. 'code' => $discount->code->code,
  170. 'label' => $discount->code->label($language),
  171. 'amount' => $discount->amount / 100,
  172. // Why it does not count yet, for example "Spend at least RM 50.00 ...".
  173. 'message' => $discount->problem === null ? null : StorefrontText::line($language, $discount->problem, [
  174. ':amount' => 'RM '.number_format((int) $discount->code->minimum_subtotal / 100, 2),
  175. ]),
  176. ],
  177. // Products after the discount, before shipping.
  178. 'total' => ($subtotal - ($discount !== null ? $discount->amount : 0)) / 100,
  179. 'adjusted' => $this->adjusted || $this->discountRemoved,
  180. 'lines' => $lines->map(fn (array $line) => [
  181. 'product' => $line['product']->toStorefront(),
  182. 'quantity' => $line['quantity'],
  183. 'max' => min($line['product']->stock, self::MAX_QUANTITY),
  184. 'line_total' => $line['line_total'] / 100,
  185. ])->values()->all(),
  186. ];
  187. }
  188. /**
  189. * @return array<int, int> Product id to quantity.
  190. */
  191. private function quantities(): array
  192. {
  193. $saved = $this->session->get($this->key(), []);
  194. if (! is_array($saved)) {
  195. return [];
  196. }
  197. $clean = [];
  198. foreach ($saved as $productId => $quantity) {
  199. if (is_int($productId) && is_int($quantity) && $quantity > 0) {
  200. $clean[$productId] = $quantity;
  201. }
  202. }
  203. return $clean;
  204. }
  205. /**
  206. * @param array<int, int> $quantities
  207. */
  208. private function save(array $quantities): void
  209. {
  210. $this->session->put($this->key(), $quantities);
  211. }
  212. private function key(): string
  213. {
  214. return 'cart.'.$this->store->id;
  215. }
  216. private function discountKey(): string
  217. {
  218. return 'cart_discount.'.$this->store->id;
  219. }
  220. }