AI store generator for ecommerce, Malaysia first. Laravel 13 + React + TypeScript.
Du kannst nicht mehr als 25 Themen auswählen Themen müssen mit entweder einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.

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