| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352 |
- <?php
-
- namespace App\Commerce;
-
- use App\Models\DiscountCode;
- use App\Models\Product;
- use App\Models\ProductVariant;
- use App\Models\Store;
- use App\Storefront\StorefrontText;
- use Illuminate\Contracts\Session\Session;
- use Illuminate\Support\Collection;
-
- /**
- * A shopper's cart for one store.
- *
- * It is kept in the browser session, so shoppers do not need an account, and each store
- * has its own cart. Only product and variant ids and quantities are saved. Names, prices and stock are
- * always read fresh from the database, so the cart can never show an old price.
- */
- class Cart
- {
- /** The most of one product a shopper may put in the cart. */
- public const int MAX_QUANTITY = 99;
-
- /** True when a quantity was lowered or an item dropped while loading, because stock or status changed. */
- private bool $adjusted = false;
-
- /** True when the discount code was taken out because it can no longer be used. */
- private bool $discountRemoved = false;
-
- public function __construct(
- private readonly Session $session,
- private readonly Store $store,
- ) {}
-
- /**
- * Put more of a product (and, for a product with options, one of its variants) in the cart.
- * Returns how many of that line are in the cart afterwards.
- */
- public function add(Product $product, ?ProductVariant $variant, int $quantity): int
- {
- $key = self::lineKey($product, $variant);
-
- return $this->store($key, ($this->quantities()[$key] ?? 0) + $quantity, $variant !== null ? $variant->stock : $product->stock);
- }
-
- /**
- * Set exactly how many of one cart line there are. Zero removes it.
- * Returns null when the line does not point at something this store sells.
- */
- public function setLine(string $key, int $quantity): ?int
- {
- $item = $this->find($key);
-
- if ($item === null) {
- return null;
- }
-
- [$product, $variant] = $item;
-
- return $this->store(self::lineKey($product, $variant), $quantity, $variant !== null ? $variant->stock : $product->stock);
- }
-
- public function removeLine(string $key): void
- {
- $quantities = $this->quantities();
- unset($quantities[$key]);
-
- $this->save($quantities);
- }
-
- /**
- * The name of a cart line: the product id, or "product-variant" for a product with options.
- */
- public static function lineKey(Product $product, ?ProductVariant $variant): string
- {
- return $variant !== null ? $product->id.'-'.$variant->id : (string) $product->id;
- }
-
- /**
- * The quantity is capped by the stock and by MAX_QUANTITY.
- */
- private function store(string $key, int $wanted, int $stock): int
- {
- $quantities = $this->quantities();
- $allowed = max(0, min($wanted, $stock, self::MAX_QUANTITY));
-
- if ($allowed === 0) {
- unset($quantities[$key]);
- } else {
- $quantities[$key] = $allowed;
- }
-
- $this->save($quantities);
-
- return $allowed;
- }
-
- /**
- * The product and variant a cart line points at, if this store sells them.
- *
- * @return array{0: Product, 1: ProductVariant|null}|null
- */
- private function find(string $key): ?array
- {
- $parsed = self::parseKey($key);
-
- if ($parsed === null) {
- return null;
- }
-
- [$productId, $variantId] = $parsed;
- $product = $this->store->products()->active()->with('variants')->whereKey($productId)->first();
-
- if ($product === null) {
- return null;
- }
-
- $variant = $variantId !== null ? $product->variants->firstWhere('id', $variantId) : null;
-
- // A product with options must name one of its variants; a simple product must not name any.
- if ($product->hasVariants() !== ($variant !== null)) {
- return null;
- }
-
- return [$product, $variant];
- }
-
- /**
- * @return array{0: int, 1: int|null}|null
- */
- private static function parseKey(string $key): ?array
- {
- if (preg_match('/^(\d+)(?:-(\d+))?$/', $key, $match) !== 1) {
- return null;
- }
-
- return [(int) $match[1], isset($match[2]) ? (int) $match[2] : null];
- }
-
- public function clear(): void
- {
- $this->session->forget($this->key());
- $this->session->forget($this->discountKey());
- }
-
- /**
- * Put a discount code in the cart. Returns the problem (a StorefrontText key) when the code
- * does not exist or cannot be used at all; a code that only needs a bigger cart is kept.
- */
- public function applyCode(string $code): ?string
- {
- $discount = $this->store->discountCodes()->where('code', DiscountCode::normalize($code))->first();
-
- if ($discount === null) {
- return 'discount_invalid';
- }
-
- $problem = $discount->problemFor((int) $this->lines()->sum('line_total'));
-
- if ($problem !== null && $problem !== 'discount_minimum') {
- return $problem;
- }
-
- $this->session->put($this->discountKey(), $discount->code);
-
- return null;
- }
-
- /**
- * True when the last discount() call took the code out because it can no longer be used.
- */
- public function discountWasRemoved(): bool
- {
- return $this->discountRemoved;
- }
-
- public function removeCode(): void
- {
- $this->session->forget($this->discountKey());
- }
-
- /**
- * The code in the cart and what it is worth for these products.
- * A code that was deleted, switched off, expired or used up is taken out, and the cart says so once.
- */
- public function discount(int $subtotal): ?AppliedDiscount
- {
- $code = $this->session->get($this->discountKey());
-
- if (! is_string($code)) {
- return null;
- }
-
- $discount = $this->store->discountCodes()->where('code', $code)->first();
- $problem = $discount?->problemFor($subtotal);
-
- if ($discount === null || ($problem !== null && $problem !== 'discount_minimum')) {
- $this->removeCode();
- $this->discountRemoved = true;
-
- return null;
- }
-
- return new AppliedDiscount($discount, $problem === null ? $discount->amountFor($subtotal) : 0, $problem);
- }
-
- /**
- * The cart lines, with fresh product details.
- * Products that are no longer for sale are dropped, and quantities above the stock are lowered.
- * A line whose variant was removed, or whose product gained or lost its options, is dropped too.
- *
- * @return Collection<int, array{key: string, product: Product, variant: ProductVariant|null, unit_price: int, quantity: int, line_total: int}>
- */
- public function lines(): Collection
- {
- $quantities = $this->quantities();
-
- if ($quantities === []) {
- return collect();
- }
-
- $productIds = array_filter(array_map(fn (string $key) => self::parseKey($key)[0] ?? null, array_keys($quantities)));
-
- $products = $this->store->products()
- ->active()
- ->with(['images', 'variants'])
- ->whereKey($productIds)
- ->get()
- ->keyBy('id');
-
- $kept = [];
- $lines = collect();
-
- foreach ($quantities as $key => $quantity) {
- [$productId, $variantId] = self::parseKey($key) ?? [0, null];
- $product = $products->get($productId);
- $variant = $product !== null && $variantId !== null ? $product->variants->firstWhere('id', $variantId) : null;
- $valid = $product !== null && $product->hasVariants() === ($variant !== null);
- $stock = $variant !== null ? $variant->stock : ($product !== null ? $product->stock : 0);
- $allowed = $valid ? min($quantity, $stock, self::MAX_QUANTITY) : 0;
-
- if ($allowed !== $quantity) {
- $this->adjusted = true;
- }
-
- if (! $valid || $allowed < 1) {
- continue;
- }
-
- $unitPrice = $variant !== null ? $variant->price : $product->price;
-
- $kept[$key] = $allowed;
- $lines->push([
- // PHP turns a session key such as "12" into the number 12; the frontend always gets text.
- 'key' => (string) $key,
- 'product' => $product,
- 'variant' => $variant,
- 'unit_price' => $unitPrice,
- 'quantity' => $allowed,
- 'line_total' => $unitPrice * $allowed,
- ]);
- }
-
- if ($kept !== $quantities) {
- $this->save($kept);
- }
-
- return $lines;
- }
-
- /**
- * What the storefront is allowed to see. Money is in ringgit here.
- *
- * @return array{count: int, subtotal: float|int, discount: array<string, mixed>|null, total: float|int, adjusted: bool, lines: array<int, array<string, mixed>>}
- */
- public function toStorefront(): array
- {
- $lines = $this->lines();
- $subtotal = (int) $lines->sum('line_total');
- $discount = $lines->isEmpty() ? null : $this->discount($subtotal);
- $language = $this->store->language->value;
-
- return [
- 'count' => (int) $lines->sum('quantity'),
- 'subtotal' => $subtotal / 100,
- 'discount' => $discount === null ? null : [
- 'code' => $discount->code->code,
- 'label' => $discount->code->label($language),
- 'amount' => $discount->amount / 100,
- // Why it does not count yet, for example "Spend at least RM 50.00 ...".
- 'message' => $discount->problem === null ? null : StorefrontText::line($language, $discount->problem, [
- ':amount' => 'RM '.number_format((int) $discount->code->minimum_subtotal / 100, 2),
- ]),
- ],
- // Products after the discount, before shipping.
- 'total' => ($subtotal - ($discount !== null ? $discount->amount : 0)) / 100,
- 'adjusted' => $this->adjusted || $this->discountRemoved,
- 'lines' => $lines->map(fn (array $line) => [
- 'key' => $line['key'],
- 'product' => $line['product']->toStorefront(),
- 'variant' => $line['variant'] !== null
- ? ['id' => $line['variant']->id, 'name' => $line['variant']->name()]
- : null,
- 'unit_price' => $line['unit_price'] / 100,
- 'quantity' => $line['quantity'],
- 'max' => min($line['variant'] !== null ? $line['variant']->stock : $line['product']->stock, self::MAX_QUANTITY),
- 'line_total' => $line['line_total'] / 100,
- ])->values()->all(),
- ];
- }
-
- /**
- * @return array<string, int> Cart line name ("12" or "12-34") to quantity.
- */
- private function quantities(): array
- {
- $saved = $this->session->get($this->key(), []);
-
- if (! is_array($saved)) {
- return [];
- }
-
- $clean = [];
-
- foreach ($saved as $key => $quantity) {
- if (self::parseKey((string) $key) !== null && is_int($quantity) && $quantity > 0) {
- $clean[(string) $key] = $quantity;
- }
- }
-
- return $clean;
- }
-
- /**
- * @param array<string, int> $quantities
- */
- private function save(array $quantities): void
- {
- $this->session->put($this->key(), $quantities);
- }
-
- private function key(): string
- {
- return 'cart.'.$this->store->id;
- }
-
- private function discountKey(): string
- {
- return 'cart_discount.'.$this->store->id;
- }
- }
|