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.

Cart.php 17KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486
  1. <?php
  2. namespace App\Commerce;
  3. use App\Models\AutomaticDiscount;
  4. use App\Models\DiscountCode;
  5. use App\Models\Order;
  6. use App\Models\Product;
  7. use App\Models\ProductVariant;
  8. use App\Models\Store;
  9. use App\Storefront\StorefrontText;
  10. use Illuminate\Contracts\Session\Session;
  11. use Illuminate\Support\Collection;
  12. /**
  13. * A shopper's cart for one store.
  14. *
  15. * It is kept in the browser session, so shoppers do not need an account, and each store
  16. * has its own cart. Only product and variant ids and quantities are saved. Names, prices and stock are
  17. * always read fresh from the database, so the cart can never show an old price.
  18. *
  19. * @phpstan-type CartLine array{key: string, product: Product, variant: ProductVariant|null, unit_price: int, quantity: int, line_total: int}
  20. */
  21. class Cart
  22. {
  23. /** The most of one product a shopper may put in the cart. */
  24. public const int MAX_QUANTITY = 99;
  25. /** True when a quantity was lowered or an item dropped while loading, because stock or status changed. */
  26. private bool $adjusted = false;
  27. /** True when the discount code was taken out because it can no longer be used. */
  28. private bool $discountRemoved = false;
  29. /** @var Collection<int, AutomaticDiscount>|null Loaded once per request. */
  30. private ?Collection $offers = null;
  31. public function __construct(
  32. private readonly Session $session,
  33. private readonly Store $store,
  34. ) {}
  35. /**
  36. * Put more of a product (and, for a product with options, one of its variants) in the cart.
  37. * Returns how many of that line are in the cart afterwards.
  38. */
  39. public function add(Product $product, ?ProductVariant $variant, int $quantity): int
  40. {
  41. $key = self::lineKey($product, $variant);
  42. return $this->store($key, ($this->quantities()[$key] ?? 0) + $quantity, $variant !== null ? $variant->stock : $product->stock);
  43. }
  44. /**
  45. * Set exactly how many of one cart line there are. Zero removes it.
  46. * Returns null when the line does not point at something this store sells.
  47. */
  48. public function setLine(string $key, int $quantity): ?int
  49. {
  50. $item = $this->find($key);
  51. if ($item === null) {
  52. return null;
  53. }
  54. [$product, $variant] = $item;
  55. return $this->store(self::lineKey($product, $variant), $quantity, $variant !== null ? $variant->stock : $product->stock);
  56. }
  57. public function removeLine(string $key): void
  58. {
  59. $quantities = $this->quantities();
  60. unset($quantities[$key]);
  61. $this->save($quantities);
  62. }
  63. /**
  64. * The name of a cart line: the product id, or "product-variant" for a product with options.
  65. */
  66. public static function lineKey(Product $product, ?ProductVariant $variant): string
  67. {
  68. return $variant !== null ? $product->id.'-'.$variant->id : (string) $product->id;
  69. }
  70. /**
  71. * The quantity is capped by the stock and by MAX_QUANTITY.
  72. */
  73. private function store(string $key, int $wanted, int $stock): int
  74. {
  75. $quantities = $this->quantities();
  76. $allowed = max(0, min($wanted, $stock, self::MAX_QUANTITY));
  77. if ($allowed === 0) {
  78. unset($quantities[$key]);
  79. } else {
  80. $quantities[$key] = $allowed;
  81. }
  82. $this->save($quantities);
  83. return $allowed;
  84. }
  85. /**
  86. * The product and variant a cart line points at, if this store sells them.
  87. *
  88. * @return array{0: Product, 1: ProductVariant|null}|null
  89. */
  90. private function find(string $key): ?array
  91. {
  92. $parsed = self::parseKey($key);
  93. if ($parsed === null) {
  94. return null;
  95. }
  96. [$productId, $variantId] = $parsed;
  97. $product = $this->store->products()->active()->with('variants')->whereKey($productId)->first();
  98. if ($product === null) {
  99. return null;
  100. }
  101. $variant = $variantId !== null ? $product->variants->firstWhere('id', $variantId) : null;
  102. // A product with options must name one of its variants; a simple product must not name any.
  103. if ($product->hasVariants() !== ($variant !== null)) {
  104. return null;
  105. }
  106. return [$product, $variant];
  107. }
  108. /**
  109. * @return array{0: int, 1: int|null}|null
  110. */
  111. private static function parseKey(string $key): ?array
  112. {
  113. if (preg_match('/^(\d+)(?:-(\d+))?$/', $key, $match) !== 1) {
  114. return null;
  115. }
  116. return [(int) $match[1], isset($match[2]) ? (int) $match[2] : null];
  117. }
  118. public function clear(): void
  119. {
  120. $this->session->forget($this->key());
  121. $this->session->forget($this->discountKey());
  122. $this->session->forget($this->unpaidOrderKey());
  123. }
  124. /**
  125. * Remember the order the shopper just placed, so the cart page can offer "Complete payment" if they leave the
  126. * payment page. Kept in this browser only, like the cart itself.
  127. */
  128. public function rememberUnpaidOrder(Order $order): void
  129. {
  130. $this->session->put($this->unpaidOrderKey(), $order->public_id);
  131. }
  132. /**
  133. * The order this shopper placed and can still pay, or null. An order that was paid or ran out of time is forgotten.
  134. */
  135. public function unpaidOrder(): ?Order
  136. {
  137. $publicId = $this->session->get($this->unpaidOrderKey());
  138. if (! is_string($publicId)) {
  139. return null;
  140. }
  141. $order = $this->store->orders()->where('public_id', $publicId)->first();
  142. if ($order === null || ! $order->canStillPay()) {
  143. $this->session->forget($this->unpaidOrderKey());
  144. return null;
  145. }
  146. return $order;
  147. }
  148. /**
  149. * Put a discount code in the cart. Returns the problem (a StorefrontText key) when the code
  150. * does not exist or cannot be used at all; a code that only needs a bigger cart is kept.
  151. */
  152. public function applyCode(string $code): ?string
  153. {
  154. $discount = $this->store->discountCodes()->where('code', DiscountCode::normalize($code))->first();
  155. if ($discount === null) {
  156. return 'discount_invalid';
  157. }
  158. $problem = $discount->problemFor((int) $this->lines()->sum('line_total'));
  159. if ($problem !== null && $problem !== 'discount_minimum') {
  160. return $problem;
  161. }
  162. $this->session->put($this->discountKey(), $discount->code);
  163. return null;
  164. }
  165. /**
  166. * True when the last discount() call took the code out because it can no longer be used.
  167. */
  168. public function discountWasRemoved(): bool
  169. {
  170. return $this->discountRemoved;
  171. }
  172. public function removeCode(): void
  173. {
  174. $this->session->forget($this->discountKey());
  175. }
  176. /**
  177. * The code in the cart and what it is worth for these products.
  178. * A code that was deleted, switched off, expired or used up is taken out, and the cart says so once.
  179. */
  180. public function discount(int $subtotal): ?AppliedDiscount
  181. {
  182. $code = $this->session->get($this->discountKey());
  183. if (! is_string($code)) {
  184. return null;
  185. }
  186. $discount = $this->store->discountCodes()->where('code', $code)->first();
  187. $problem = $discount?->problemFor($subtotal);
  188. if ($discount === null || ($problem !== null && $problem !== 'discount_minimum')) {
  189. $this->removeCode();
  190. $this->discountRemoved = true;
  191. return null;
  192. }
  193. return new AppliedDiscount($discount, $problem === null ? $discount->amountFor($subtotal) : 0, $problem);
  194. }
  195. /**
  196. * Automatic discounts that are on and within their dates, biggest first.
  197. *
  198. * @return Collection<int, AutomaticDiscount>
  199. */
  200. public function liveOffers(): Collection
  201. {
  202. return $this->offers ??= $this->store->automaticDiscounts()
  203. ->where('active', true)
  204. ->orderByDesc('value')
  205. ->get()
  206. ->filter(fn (AutomaticDiscount $offer) => $offer->isLive())
  207. ->values()
  208. ->toBase();
  209. }
  210. /**
  211. * The one discount these lines get: the code or the best automatic discount, whichever saves more.
  212. * Only one applies, so a code and a sale never add up to more than the merchant planned.
  213. *
  214. * @param Collection<int, array{key: string, product: Product, variant: ProductVariant|null, unit_price: int, quantity: int, line_total: int}> $lines
  215. */
  216. public function applied(Collection $lines): ?CartDiscount
  217. {
  218. if ($lines->isEmpty()) {
  219. return null;
  220. }
  221. $code = $this->discount((int) $lines->sum('line_total'));
  222. $codeAmount = $code !== null && $code->problem === null ? $code->amount : 0;
  223. $best = null;
  224. $bestAmount = 0;
  225. foreach ($this->liveOffers() as $offer) {
  226. $amount = $offer->amountFor($lines);
  227. if ($amount > $bestAmount) {
  228. [$best, $bestAmount] = [$offer, $amount];
  229. }
  230. }
  231. if ($best !== null && $bestAmount > $codeAmount) {
  232. return new CartDiscount($bestAmount, offer: $best);
  233. }
  234. return $code !== null && $codeAmount > 0 ? new CartDiscount($codeAmount, code: $code->code) : null;
  235. }
  236. /**
  237. * A nudge such as "Add 1 more to get 10% off (Raya Sale)", for an automatic discount the cart
  238. * has started on but does not reach yet. Null when there is nothing worth saying.
  239. *
  240. * @param Collection<int, array{key: string, product: Product, variant: ProductVariant|null, unit_price: int, quantity: int, line_total: int}> $lines
  241. */
  242. private function offerHint(Collection $lines, ?CartDiscount $applied): ?string
  243. {
  244. $language = $this->store->language->value;
  245. foreach ($this->liveOffers() as $offer) {
  246. $shortfall = $offer->shortfall($lines);
  247. if ($shortfall === null || $offer->eligible($lines)->isEmpty() || $applied?->offer?->is($offer)) {
  248. continue;
  249. }
  250. $replace = [':label' => $offer->label($language), ':name' => $offer->name];
  251. return isset($shortfall['items'])
  252. ? StorefrontText::line($language, 'offer_add_items', [...$replace, ':count' => (string) $shortfall['items']])
  253. : StorefrontText::line($language, 'offer_spend_more', [...$replace, ':amount' => 'RM '.number_format(($shortfall['amount'] ?? 0) / 100, 2)]);
  254. }
  255. return null;
  256. }
  257. /**
  258. * The cart lines, with fresh product details.
  259. * Products that are no longer for sale are dropped, and quantities above the stock are lowered.
  260. * A line whose variant was removed, or whose product gained or lost its options, is dropped too.
  261. *
  262. * @return Collection<int, array{key: string, product: Product, variant: ProductVariant|null, unit_price: int, quantity: int, line_total: int}>
  263. */
  264. public function lines(): Collection
  265. {
  266. $quantities = $this->quantities();
  267. if ($quantities === []) {
  268. return collect();
  269. }
  270. $productIds = array_filter(array_map(fn (string $key) => self::parseKey($key)[0] ?? null, array_keys($quantities)));
  271. $products = $this->store->products()
  272. ->active()
  273. ->with(Product::STOREFRONT_RELATIONS)
  274. ->whereKey($productIds)
  275. ->get()
  276. ->keyBy('id');
  277. $kept = [];
  278. $lines = collect();
  279. foreach ($quantities as $key => $quantity) {
  280. [$productId, $variantId] = self::parseKey($key) ?? [0, null];
  281. $product = $products->get($productId);
  282. $variant = $product !== null && $variantId !== null ? $product->variants->firstWhere('id', $variantId) : null;
  283. $valid = $product !== null && $product->hasVariants() === ($variant !== null);
  284. $stock = $variant !== null ? $variant->stock : ($product !== null ? $product->stock : 0);
  285. $allowed = $valid ? min($quantity, $stock, self::MAX_QUANTITY) : 0;
  286. if ($allowed !== $quantity) {
  287. $this->adjusted = true;
  288. }
  289. if (! $valid || $allowed < 1) {
  290. continue;
  291. }
  292. $unitPrice = $variant !== null ? $variant->price : $product->price;
  293. $kept[$key] = $allowed;
  294. $lines->push([
  295. // PHP turns a session key such as "12" into the number 12; the frontend always gets text.
  296. 'key' => (string) $key,
  297. 'product' => $product,
  298. 'variant' => $variant,
  299. 'unit_price' => $unitPrice,
  300. 'quantity' => $allowed,
  301. 'line_total' => $unitPrice * $allowed,
  302. ]);
  303. }
  304. if ($kept !== $quantities) {
  305. $this->save($kept);
  306. }
  307. return $lines;
  308. }
  309. /**
  310. * What the storefront is allowed to see. Money is in ringgit here.
  311. *
  312. * @return array{count: int, subtotal: float|int, discount: array<string, mixed>|null, applied: array<string, mixed>|null, offer_hint: string|null, total: float|int, adjusted: bool, lines: array<int, array<string, mixed>>}
  313. */
  314. public function toStorefront(): array
  315. {
  316. $lines = $this->lines();
  317. $subtotal = (int) $lines->sum('line_total');
  318. $applied = $this->applied($lines);
  319. $discount = $lines->isEmpty() ? null : $this->discount($subtotal);
  320. $language = $this->store->language->value;
  321. // The code works, but an automatic discount saves more, so the code is not used.
  322. $codeBeaten = $discount !== null && $discount->problem === null && $applied?->offer !== null;
  323. return [
  324. 'count' => (int) $lines->sum('quantity'),
  325. 'subtotal' => $subtotal / 100,
  326. 'discount' => $discount === null ? null : [
  327. 'code' => $discount->code->code,
  328. 'label' => $discount->code->label($language),
  329. 'amount' => $discount->amount / 100,
  330. // Why it does not count, for example "Spend at least RM 50.00 ..." or "Raya Sale saves you more".
  331. 'message' => match (true) {
  332. $codeBeaten => StorefrontText::line($language, 'discount_offer_better', [':name' => $applied->name()]),
  333. $discount->problem === null => null,
  334. default => StorefrontText::line($language, $discount->problem, [
  335. ':amount' => 'RM '.number_format((int) $discount->code->minimum_subtotal / 100, 2),
  336. ]),
  337. },
  338. ],
  339. // The discount actually taken off: the code, or an automatic discount.
  340. 'applied' => $applied === null ? null : [
  341. 'name' => $applied->name(),
  342. 'amount' => $applied->amount / 100,
  343. 'automatic' => $applied->offer !== null,
  344. ],
  345. 'offer_hint' => $this->offerHint($lines, $applied),
  346. // Products after the discount, before shipping.
  347. 'total' => ($subtotal - ($applied !== null ? $applied->amount : 0)) / 100,
  348. 'adjusted' => $this->adjusted || $this->discountRemoved,
  349. 'lines' => $lines->map(fn (array $line) => [
  350. 'key' => $line['key'],
  351. 'product' => $line['product']->toStorefront(),
  352. 'variant' => $line['variant'] !== null
  353. ? ['id' => $line['variant']->id, 'name' => $line['variant']->name()]
  354. : null,
  355. 'unit_price' => $line['unit_price'] / 100,
  356. 'quantity' => $line['quantity'],
  357. 'max' => min($line['variant'] !== null ? $line['variant']->stock : $line['product']->stock, self::MAX_QUANTITY),
  358. 'line_total' => $line['line_total'] / 100,
  359. ])->values()->all(),
  360. ];
  361. }
  362. /**
  363. * @return array<string, int> Cart line name ("12" or "12-34") to quantity.
  364. */
  365. private function quantities(): array
  366. {
  367. $saved = $this->session->get($this->key(), []);
  368. if (! is_array($saved)) {
  369. return [];
  370. }
  371. $clean = [];
  372. foreach ($saved as $key => $quantity) {
  373. if (self::parseKey((string) $key) !== null && is_int($quantity) && $quantity > 0) {
  374. $clean[(string) $key] = $quantity;
  375. }
  376. }
  377. return $clean;
  378. }
  379. /**
  380. * @param array<string, int> $quantities
  381. */
  382. private function save(array $quantities): void
  383. {
  384. $this->session->put($this->key(), $quantities);
  385. }
  386. private function key(): string
  387. {
  388. return 'cart.'.$this->store->id;
  389. }
  390. private function discountKey(): string
  391. {
  392. return 'cart_discount.'.$this->store->id;
  393. }
  394. private function unpaidOrderKey(): string
  395. {
  396. return 'unpaid_order.'.$this->store->id;
  397. }
  398. }