store(($this->quantities()[$product->id] ?? 0) + $quantity, $product); } /** * Set exactly how many of a product are in the cart. Zero removes it. * The number is capped by the stock and by MAX_QUANTITY. */ public function set(Product $product, int $quantity): int { return $this->store($quantity, $product); } private function store(int $wanted, Product $product): int { $quantities = $this->quantities(); $allowed = max(0, min($wanted, $product->stock, self::MAX_QUANTITY)); if ($allowed === 0) { unset($quantities[$product->id]); } else { $quantities[$product->id] = $allowed; } $this->save($quantities); return $allowed; } public function remove(int $productId): void { $quantities = $this->quantities(); unset($quantities[$productId]); $this->save($quantities); } 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. * * @return Collection */ public function lines(): Collection { $quantities = $this->quantities(); if ($quantities === []) { return collect(); } $products = $this->store->products() ->active() ->with('images') ->whereKey(array_keys($quantities)) ->get() ->keyBy('id'); $kept = []; $lines = collect(); foreach ($quantities as $productId => $quantity) { $product = $products->get($productId); $allowed = $product ? min($quantity, $product->stock, self::MAX_QUANTITY) : 0; if ($allowed !== $quantity) { $this->adjusted = true; } if ($product === null || $allowed < 1) { continue; } $kept[$productId] = $allowed; $lines->push([ 'product' => $product, 'quantity' => $allowed, 'line_total' => $product->price * $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|null, total: float|int, adjusted: bool, lines: array>} */ 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) => [ 'product' => $line['product']->toStorefront(), 'quantity' => $line['quantity'], 'max' => min($line['product']->stock, self::MAX_QUANTITY), 'line_total' => $line['line_total'] / 100, ])->values()->all(), ]; } /** * @return array Product id to quantity. */ private function quantities(): array { $saved = $this->session->get($this->key(), []); if (! is_array($saved)) { return []; } $clean = []; foreach ($saved as $productId => $quantity) { if (is_int($productId) && is_int($quantity) && $quantity > 0) { $clean[$productId] = $quantity; } } return $clean; } /** * @param array $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; } }