AI store generator for ecommerce, Malaysia first. Laravel 13 + React + TypeScript.
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

Cart.php 15KB

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