Output:
Chunk ID: d8aef4
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 1715
Output:
<?php

namespace App\Livewire\Storefront\Cart;

use App\Exceptions\InvalidDiscountException;
use App\Models\Cart;
use App\Models\CartLine;
use App\Models\Customer;
use App\Models\ShippingRate;
use App\Models\Store;
use App\Services\CartService;
use App\Services\DiscountService;
use App\Services\ShippingCalculator;
use App\ValueObjects\DiscountResult;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Auth;
use Illuminate\Validation\ValidationException;
use Livewire\Attributes\On;
use Livewire\Component;

class Show extends Component
{
    public int $storeId;

    public string $discountCode = '';

    public ?string $appliedDiscountCode = null;

    public string $shippingCountry = 'DE';

    public string $shippingPostalCode = '';

    public string $shippingProvinceCode = '';

    public function mount(): void
    {
        $this->storeId = $this->store()->getKey();
        $this->appliedDiscountCode = trim((string) session('cart_discount_code')) ?: null;
        $this->discountCode = $this->appliedDiscountCode ?? '';
    }

    #[On('cart-updated')]
    public function refreshCart(): void {}

    public function increaseQuantity(int $lineId): void
    {
        $line = $this->cartLine($lineId);

        if (! $line instanceof CartLine) {
            return;
        }

        app(CartService::class)->updateLineQuantity($line->cart, $line->getKey(), $line->quantity + 1);
        $this->dispatch('cart-updated');
    }

    public function decreaseQuantity(int $lineId): void
    {
        $line = $this->cartLine($lineId);

        if (! $line instanceof CartLine) {
            return;
        }

        app(CartService::class)->updateLineQuantity($line->cart, $line->getKey(), $line->quantity - 1);
        $this->dispatch('cart-updated');
    }

    public function removeLine(int $lineId): void
    {
        $line = $this->cartLine($lineId);

        if (! $line instanceof CartLine) {
            return;
        }

        app(CartService::class)->removeLine($line->cart, $line->getKey());
        $this->dispatch('cart-updated');
    }

    public function applyDiscount(): void
    {
        $this->validate([
            'discountCode' => ['required', 'string', 'max:50'],
        ]);

        $cart = $this->cart();

        if (! $cart instanceof Cart) {
            return;
        }

        $code = trim($this->discountCode);

        try {
            $discount = app(DiscountService::class)->validate($code, $this->store(), $cart);
            app(DiscountService::class)->calculate($discount, $this->subtotal(), $this->lines()->all());
        } catch (InvalidDiscountException $exception) {
            $this->removeDiscount();

            throw ValidationException::withMessages([
                'discountCode' => $exception->getMessage(),
            ]);
        }

        $this->appliedDiscountCode = $code;
        $this->discountCode = $code;
        session(['cart_discount_code' => $code]);
        $this->resetErrorBag('discountCode');
    }

    public function removeDiscount(): void
    {
        $this->appliedDiscountCode = null;
        $this->discountCode = '';
        session()->forget('cart_discount_code');
        $this->resetErrorBag('discountCode');
    }

    public function estimateShipping(): void
    {
        $this->validate([
            'shippingCountry' => ['required', 'string', 'size:2'],
            'shippingPostalCode' => ['nullable', 'string', 'max:20'],
            'shippingProvinceCode' => ['nullable', 'string', 'max:20'],
        ]);

        $this->resetErrorBag('shippingCountry');
    }

    public function checkout(): void
    {
        if ($this->lineCount() === 0) {
            return;
        }

        $this->redirectRoute('checkout.show', navigate: true);
    }

    public function store(): Store
    {
        if (isset($this->storeId)) {
            $store = Store::query()->findOrFail($this->storeId);
            app()->instance('current_store', $store);

            return $store;
        }

        $store = app('current_store');

        abort_unless($store instanceof Store, 404);

        return $store;
    }

    public function cart(): ?Cart
    {
        $cart = app(CartService::class)->currentForSession($this->store(), $this->customer());

        return $cart?->load([
            'lines.variant.product',
            'lines.variant.optionValues.option',
        ]);
    }

    /**
     * @return Collection<int, CartLine>
     */
    public function lines(): Collection
    {
        return $this->cart()?->lines->sortBy('id')->values() ?? collect();
    }

    public function lineCount(): int
    {
        return $this->lines()->sum('quantity');
    }

    public function subtotal(): int
    {
        return $this->lines()->sum('line_subtotal_amount');
    }

    /**
     * @return Collection<int, ShippingRate>
     */
    public function availableRates(): Collection
    {
        if (! $this->requiresShipping() || $this->shippingCountry === '') {
            return collect();
        }

        return app(ShippingCalculator::class)->getAvailableRates($this->store(), $this->shippingAddress());
    }

    public function requiresShipping(): bool
    {
        $cart = $this->cart();

        return $cart instanceof Cart && app(ShippingCalculator::class)->requiresShipping($cart);
    }

    /**
     * @return array<int, int>
     */
    public function shippingRateAmounts(): array
    {
        $cart = $this->cart();

        if (! $cart instanceof Cart) {
            return [];
        }

        return $this->availableRates()
            ->mapWithKeys(fn (ShippingRate $rate): array => [
                $rate->getKey() => app(ShippingCalculator::class)->calculate($rate, $cart) ?? 0,
            ])
            ->all();
    }

    public function estimatedShippingAmount(): ?int
    {
        if (! $this->requiresShipping()) {
            return 0;
        }

        $amounts = $this->shippingRateAmounts();

        return $amounts === [] ? null : min($amounts);
    }

    public function discountResult(): ?DiscountResult
    {
        $cart = $this->cart();
        $code = trim((string) $this->appliedDiscountCode);

        if (! $cart instanceof Cart || $code === '') {
            return null;
        }

        try {
            $discount = app(DiscountService::class)->validate($code, $this->store(), $cart);

            return app(DiscountService::class)->calculate($discount, $this->subtotal(), $this->lines()->all());
        } catch (InvalidDiscountException) {
            return null;
        }
    }

    public function discountAmount(): int
    {
        return $this->discountResult()?->amount ?? 0;
    }

    public function discountFreeShipping(): bool
    {
        return $this->discountResult()?->freeShipping ?? false;
    }

    public function estimatedTotal(): int


Output:
Chunk ID: c1d409
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 1369
Output:
<?php

namespace App\Livewire\Storefront\Products;

use App\Enums\InventoryPolicy;
use App\Models\Customer;
use App\Models\Product;
use App\Models\ProductOptionValue;
use App\Models\ProductVariant;
use App\Models\Store;
use App\Services\CartService;
use Illuminate\Support\Facades\Auth;
use Livewire\Component;

class Show extends Component
{
    public string $handle;

    public int $storeId;

    /**
     * @var array<string, string>
     */
    public array $selectedOptions = [];

    public int $quantity = 1;

    public function mount(string $handle): void
    {
        $this->handle = $handle;
        $this->storeId = $this->store()->getKey();

        $variant = $this->product()->variants->firstWhere('is_default', true)
            ?? $this->product()->variants->first();

        if ($variant instanceof ProductVariant) {
            $this->selectedOptions = $variant->optionValues
                ->mapWithKeys(fn (ProductOptionValue $value): array => [$value->option->name => $value->value])
                ->all();
        }
    }

    public function selectOption(string $optionName, string $value): void
    {
        $this->selectedOptions[$optionName] = $value;
        $this->quantity = 1;
    }

    public function increaseQuantity(): void
    {
        $variant = $this->selectedVariant();
        $max = $variant?->inventoryItem?->policy === InventoryPolicy::Deny
            ? max(1, $variant->inventoryItem->availableQuantity())
            : null;

        if ($max === null || $this->quantity < $max) {
            $this->quantity++;
        }
    }

    public function decreaseQuantity(): void
    {
        $this->quantity = max(1, $this->quantity - 1);
    }

    public function addToCart(): void
    {
        $store = $this->store();
        $variant = $this->selectedVariant();

        if (! $variant instanceof ProductVariant || ! $this->canAddToCart()) {
            return;
        }

        $customer = Auth::guard('customer')->user();
        $customer = $customer instanceof Customer ? $customer : null;

        app(CartService::class)->addLine(
            app(CartService::class)->getOrCreateForSession($store, $customer),
            $variant->getKey(),
            $this->quantity,
        );

        $this->dispatch('cart-updated');
        $this->dispatch('toast', type: 'success', message: __('Added to cart'));
    }

    public function store(): Store
    {
        if (isset($this->storeId)) {
            $store = Store::query()->findOrFail($this->storeId);
            app()->instance('current_store', $store);

            return $store;
        }

        $store = app('current_store');

        abort_unless($store instanceof Store, 404);

        return $store;
    }

    public function product(): Product
    {
        $this->store();

        return Product::query()
            ->with(['options.values', 'variants.inventoryItem', 'variants.optionValues.option', 'collections'])
            ->where('handle', $this->handle)
            ->where('status', 'active')
            ->whereNotNull('published_at')
            ->firstOrFail();
    }

    public function selectedVariant(): ?ProductVariant
    {
        $product = $this->product();

        if ($product->options->isEmpty()) {
            return $product->variants->first();
        }

        return $product->variants->first(function (ProductVariant $variant): bool {
            $options = $variant->optionValues
                ->mapWithKeys(fn (ProductOptionValue $value): array => [$value->option->name => $value->value])
                ->all();

            return $options === $this->selectedOptions;
        });
    }

    public function canAddToCart(): bool
    {
        $variant = $this->selectedVariant();

        if (! $variant instanceof ProductVariant || ! $variant->isPurchasable()) {
            return false;
        }

        $inventory = $variant->inventoryItem;

        return $inventory?->policy === InventoryPolicy::Continue
            || ($inventory?->availableQuantity() ?? 0) >= $this->quantity;
    }

    /**
     * @return array{message: string, class: string}
     */
    public function stockState(): array
    {
        $variant = $this->selectedVariant();
        $inventory = $variant?->inventoryItem;

        if (! $inventory) {
            return ['message' => 'Unavailable', 'class' => 'text-red-700 dark:text-red-300'];
        }

        if ($inventory->policy === InventoryPolicy::Continue && $inventory->availableQuantity() <= 0) {
            return ['message' => 'Available on backorder', 'class' => 'text-blue-700 dark:text-blue-300'];
        }

        if ($inventory->availableQuantity() <= 0) {
            return ['message' => 'Out of stock', 'class' => 'text-red-700 dark:text-red-300'];
        }

        if ($inventory->availableQuantity() <= 10) {
            return ['message' => "Only {$inventory->availableQuantity()} left in stock", 'class' => 'text-amber-700 dark:text-amber-300'];
        }

        return ['message' => 'In stock', 'class' => 'text-green-700 dark:text-green-300'];
    }

    public function render(): mixed
    {
        $product = $this->product();

        return view('livewire.storefront.products.show', [
            'product' => $product,
            'selectedVariant' => $this->selectedVariant(),
            'stockState' => $this->stockState(),
        ])->layout('layouts.storefront', [
            'title' => $product->title,
        ]);
    }
}


I’ve got the Suite 8 requirements and the cart/product Livewire code. The cart page already has the core behavior, but the UI text differs from the spec in a few places, so I’m going to write tests around the implemented customer-facing copy unless a spec-facing label is missing enough to warrant a small view adjustment.


sed -n '260,560p' app/Livewire/Storefront/Cart/Show.php


sed -n '260,560p' app/Livewire/Storefront/Cart/Show.php

    public function estimatedTotal(): int
    {
        $shipping = $this->discountFreeShipping() ? 0 : ($this->estimatedShippingAmount() ?? 0);

        return max(0, $this->subtotal() - $this->discountAmount() + $shipping);
    }

    public function render(): mixed
    {
        return view('livewire.storefront.cart.show', [
            'cart' => $this->cart(),
            'lines' => $this->lines(),
            'lineCount' => $this->lineCount(),
            'subtotal' => $this->subtotal(),
            'discountAmount' => $this->discountAmount(),
            'discountFreeShipping' => $this->discountFreeShipping(),
            'rates' => $this->availableRates(),
            'rateAmounts' => $this->shippingRateAmounts(),
            'estimatedShipping' => $this->estimatedShippingAmount(),
            'estimatedTotal' => $this->estimatedTotal(),
            'requiresShipping' => $this->requiresShipping(),
        ])->layout('layouts.storefront', [
            'title' => 'Cart',
        ]);
    }

    private function customer(): ?Customer
    {
        $customer = Auth::guard('customer')->user();

        return $customer instanceof Customer ? $customer : null;
    }

    private function cartLine(int $lineId): ?CartLine
    {
        return $this->lines()->firstWhere('id', $lineId);
    }

    /**
     * @return array<string, string>
     */
    private function shippingAddress(): array
    {
        return [
            'country' => strtoupper($this->shippingCountry),
            'country_code' => strtoupper($this->shippingCountry),
            'postal_code' => $this->shippingPostalCode,
            'province_code' => strtoupper($this->shippingProvinceCode),
        ];
    }
}


Output:
Chunk ID: 4a6b5b
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 427
Output:
    public function estimatedTotal(): int
    {
        $shipping = $this->discountFreeShipping() ? 0 : ($this->estimatedShippingAmount() ?? 0);

        return max(0, $this->subtotal() - $this->discountAmount() + $shipping);
    }

    public function render(): mixed
    {
        return view('livewire.storefront.cart.show', [
            'cart' => $this->cart(),
            'lines' => $this->lines(),
            'lineCount' => $this->lineCount(),
            'subtotal' => $this->subtotal(),
            'discountAmount' => $this->discountAmount(),
            'discountFreeShipping' => $this->discountFreeShipping(),
            'rates' => $this->availableRates(),
            'rateAmounts' => $this->shippingRateAmounts(),
            'estimatedShipping' => $this->estimatedShippingAmount(),
            'estimatedTotal' => $this->estimatedTotal(),
            'requiresShipping' => $this->requiresShipping(),
        ])->layout('layouts.storefront', [
            'title' => 'Cart',
        ]);
    }

    private function customer(): ?Customer
    {
        $customer = Auth::guard('customer')->user();

        return $customer instanceof Customer ? $customer : null;
    }

    private function cartLine(int $lineId): ?CartLine
    {
        return $this->lines()->firstWhere('id', $lineId);
    }

    /**
     * @return array<string, string>
     */
    private function shippingAddress(): array
    {
        return [
            'country' => strtoupper($this->shippingCountry),
            'country_code' => strtoupper($this->shippingCountry),
            'postal_code' => $this->shippingPostalCode,
            'province_code' => strtoupper($this->shippingProvinceCode),
        ];
    }
}


sed -n '1,300p' resources/views/livewire/storefront/cart-drawer.blade.php && sed -n '1,260p' app/Livewire/Storefront/CartDrawer.php


sed -n '1,300p' resources/views/livewire/storefront/cart-drawer.blade.php && sed -n '1,260p' app/Livewire/Storefront/CartDrawer.php

CartDrawer.php

<flux:modal name="cart-drawer" class="md:w-[32rem]">

                <flux:heading size="lg">Cart</flux:heading>
                <flux:text class="mt-1">{{ $lineCount }} {{ Str::plural('item', $lineCount) }}</flux:text>

            <flux:button :href="route('cart.show')" wire:navigate variant="subtle" size="sm" icon="shopping-bag">
                View cart
            </flux:button>

        @if ($lines->isEmpty())

                <flux:icon name="shopping-bag" class="mx-auto size-10 text-zinc-400 dark:text-zinc-600" />

Your cart is empty.

                <flux:button :href="route('collections.index')" wire:navigate variant="primary" class="mt-5">
                    Browse products
                </flux:button>

        @else

                @foreach ($lines as $line)

getKey() }}">
                        variant->product->handle) }}" wire:navigate class="flex size-16 shrink-0 items-center justify-center rounded-md border border-zinc-200 bg-zinc-100 text-zinc-400 dark:border-zinc-800 dark:bg-zinc-900 dark:text-zinc-600">
                            <flux:icon name="shopping-bag" class="size-6" />

                                    variant->product->handle) }}" wire:navigate class="line-clamp-2 text-sm font-medium text-zinc-950 hover:underline dark:text-white">
                                        {{ $line->variant->product->title }}

                                        {{ $line->variant->optionValues->map(fn ($value) => $value->option->name.': '.$value->value)->implode(' / ') ?: ($line->variant->sku ?: 'Default') }}

                                <x-storefront.price :amount="$line->line_total_amount" :currency="$cart->currency" class="justify-end text-sm" />

                                    <button type="button" wire:click="decreaseQuantity({{ $line->getKey() }})" class="flex size-9 items-center justify-center border-r border-zinc-200 text-sm dark:border-zinc-700" aria-label="Decrease {{ $line->variant->product->title }} quantity">-</button>
                                    {{ $line->quantity }}
                                    <button type="button" wire:click="increaseQuantity({{ $line->getKey() }})" class="flex size-9 items-center justify-center border-l border-zinc-200 text-sm dark:border-zinc-700" aria-label="Increase {{ $line->variant->product->title }} quantity">+</button>

                                <flux:button wire:click="removeLine({{ $line->getKey() }})" variant="ghost" size="sm" icon="trash" aria-label="Remove {{ $line->variant->product->title }}" />

                @endforeach

                    Subtotal
                    <x-storefront.price :amount="$subtotal" :currency="$cart->currency" />

                <flux:button wire:click="checkout" variant="primary" class="w-full">
                    Checkout
                </flux:button>

        @endif

</flux:modal>
<?php

namespace App\Livewire\Storefront;

use App\Models\Cart;
use App\Models\CartLine;
use App\Models\Customer;
use App\Models\Store;
use App\Services\CartService;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Auth;
use Livewire\Attributes\On;
use Livewire\Component;

class CartDrawer extends Component
{
    public int $storeId;

    public function mount(): void
    {
        $this->storeId = $this->store()->getKey();
    }

    #[On('cart-updated')]
    public function refreshCart(): void {}

    public function increaseQuantity(int $lineId): void
    {
        $line = $this->cartLine($lineId);

        if (! $line instanceof CartLine) {
            return;
        }

        app(CartService::class)->updateLineQuantity($line->cart, $line->getKey(), $line->quantity + 1);
        $this->dispatch('cart-updated');
    }

    public function decreaseQuantity(int $lineId): void
    {
        $line = $this->cartLine($lineId);

        if (! $line instanceof CartLine) {
            return;
        }

        app(CartService::class)->updateLineQuantity($line->cart, $line->getKey(), $line->quantity - 1);
        $this->dispatch('cart-updated');
    }

    public function removeLine(int $lineId): void
    {
        $line = $this->cartLine($lineId);

        if (! $line instanceof CartLine) {
            return;
        }

        app(CartService::class)->removeLine($line->cart, $line->getKey());
        $this->dispatch('cart-updated');
    }

    public function checkout(): void
    {
        if ($this->lineCount() === 0) {
            return;
        }

        $this->redirectRoute('checkout.show', navigate: true);
    }

    public function store(): Store
    {
        if (isset($this->storeId)) {
            $store = Store::query()->findOrFail($this->storeId);
            app()->instance('current_store', $store);

            return $store;
        }

        $store = app('current_store');

        abort_unless($store instanceof Store, 404);

        return $store;
    }

    public function cart(): ?Cart
    {
        $cart = app(CartService::class)->currentForSession($this->store(), $this->customer());

        return $cart?->load([
            'lines.variant.product',
            'lines.variant.optionValues.option',
        ]);
    }

    /**
     * @return Collection<int, CartLine>
     */
    public function lines(): Collection
    {
        return $this->cart()?->lines->sortBy('id')->values() ?? collect();
    }

    public function lineCount(): int
    {
        return $this->lines()->sum('quantity');
    }

    public function subtotal(): int
    {
        return $this->lines()->sum('line_subtotal_amount');
    }

    public function render(): mixed
    {
        return view('livewire.storefront.cart-drawer', [
            'cart' => $this->cart(),
            'lines' => $this->lines(),
            'lineCount' => $this->lineCount(),
            'subtotal' => $this->subtotal(),
        ]);
    }

    private function customer(): ?Customer
    {
        $customer = Auth::guard('customer')->user();

        return $customer instanceof Customer ? $customer : null;
    }

    private function cartLine(int $lineId): ?CartLine
    {
        return $this->lines()->firstWhere('id', $lineId);
    }
}


Output:
Chunk ID: effbbc
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 1972
Output:
<flux:modal name="cart-drawer" class="md:w-[32rem]">

                <flux:heading size="lg">Cart</flux:heading>
                <flux:text class="mt-1">{{ $lineCount }} {{ Str::plural('item', $lineCount) }}</flux:text>

            <flux:button :href="route('cart.show')" wire:navigate variant="subtle" size="sm" icon="shopping-bag">
                View cart
            </flux:button>

        @if ($lines->isEmpty())

                <flux:icon name="shopping-bag" class="mx-auto size-10 text-zinc-400 dark:text-zinc-600" />

Your cart is empty.

                <flux:button :href="route('collections.index')" wire:navigate variant="primary" class="mt-5">
                    Browse products
                </flux:button>

        @else

                @foreach ($lines as $line)

getKey() }}">
                        variant->product->handle) }}" wire:navigate class="flex size-16 shrink-0 items-center justify-center rounded-md border border-zinc-200 bg-zinc-100 text-zinc-400 dark:border-zinc-800 dark:bg-zinc-900 dark:text-zinc-600">
                            <flux:icon name="shopping-bag" class="size-6" />

                                    variant->product->handle) }}" wire:navigate class="line-clamp-2 text-sm font-medium text-zinc-950 hover:underline dark:text-white">
                                        {{ $line->variant->product->title }}

                                        {{ $line->variant->optionValues->map(fn ($value) => $value->option->name.': '.$value->value)->implode(' / ') ?: ($line->variant->sku ?: 'Default') }}

                                <x-storefront.price :amount="$line->line_total_amount" :currency="$cart->currency" class="justify-end text-sm" />

                                    <button type="button" wire:click="decreaseQuantity({{ $line->getKey() }})" class="flex size-9 items-center justify-center border-r border-zinc-200 text-sm dark:border-zinc-700" aria-label="Decrease {{ $line->variant->product->title }} quantity">-</button>
                                    {{ $line->quantity }}
                                    <button type="button" wire:click="increaseQuantity({{ $line->getKey() }})" class="flex size-9 items-center justify-center border-l border-zinc-200 text-sm dark:border-zinc-700" aria-label="Increase {{ $line->variant->product->title }} quantity">+</button>

                                <flux:button wire:click="removeLine({{ $line->getKey() }})" variant="ghost" size="sm" icon="trash" aria-label="Remove {{ $line->variant->product->title }}" />

                @endforeach

                    Subtotal
                    <x-storefront.price :amount="$subtotal" :currency="$cart->currency" />

                <flux:button wire:click="checkout" variant="primary" class="w-full">
                    Checkout
                </flux:button>

        @endif

</flux:modal>
<?php

namespace App\Livewire\Storefront;

use App\Models\Cart;
use App\Models\CartLine;
use App\Models\Customer;
use App\Models\Store;
use App\Services\CartService;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\Auth;
use Livewire\Attributes\On;
use Livewire\Component;

class CartDrawer extends Component
{
    public int $storeId;

    public function mount(): void
    {
        $this->storeId = $this->store()->getKey();
    }

    #[On('cart-updated')]
    public function refreshCart(): void {}

    public function increaseQuantity(int $lineId): void
    {
        $line = $this->cartLine($lineId);

        if (! $line instanceof CartLine) {
            return;
        }

        app(CartService::class)->updateLineQuantity($line->cart, $line->getKey(), $line->quantity + 1);
        $this->dispatch('cart-updated');
    }

    public function decreaseQuantity(int $lineId): void
    {
        $line = $this->cartLine($lineId);

        if (! $line instanceof CartLine) {
            return;
        }

        app(CartService::class)->updateLineQuantity($line->cart, $line->getKey(), $line->quantity - 1);
        $this->dispatch('cart-updated');
    }

    public function removeLine(int $lineId): void
    {
        $line = $this->cartLine($lineId);

        if (! $line instanceof CartLine) {
            return;
        }

        app(CartService::class)->removeLine($line->cart, $line->getKey());
        $this->dispatch('cart-updated');
    }

    public function checkout(): void
    {
        if ($this->lineCount() === 0) {
            return;
        }

        $this->redirectRoute('checkout.show', navigate: true);
    }

    public function store(): Store
    {
        if (isset($this->storeId)) {
            $store = Store::query()->findOrFail($this->storeId);
            app()->instance('current_store', $store);

            return $store;
        }

        $store = app('current_store');

        abort_unless($store instanceof Store, 404);

        return $store;
    }

    public function cart(): ?Cart
    {
        $cart = app(CartService::class)->currentForSession($this->store(), $this->customer());

        return $cart?->load([
            'lines.variant.product',
            'lines.variant.optionValues.option',
        ]);
    }

    /**
     * @return Collection<int, CartLine>
     */
    public function lines(): Collection
    {
        return $this->cart()?->lines->sortBy('id')->values() ?? collect();
    }

    public function lineCount(): int
    {
        return $this->lines()->sum('quantity');
    }

    public function subtotal(): int
    {
        return $this->lines()->sum('line_subtotal_amount');
    }

    public function render(): mixed
    {
        return view('livewire.storefront.cart-drawer', [
            'cart' => $this->cart(),
            'lines' => $this->lines(),
            'lineCount' => $this->lineCount(),
            'subtotal' => $this->subtotal(),
        ]);
    }

    private function customer(): ?Customer
    {
        $customer = Auth::guard('customer')->user();

        return $customer instanceof Customer ? $customer : null;
    }

    private function cartLine(int $lineId): ?CartLine
    {
        return $this->lines()->firstWhere('id', $lineId);
    }
}


sed -n '1,320p' database/seeders/DiscountSeeder.php


sed -n '1,320p' database/seeders/DiscountSeeder.php

<?php

namespace Database\Seeders;

use App\Models\Discount;
use App\Models\Store;
use Illuminate\Database\Seeder;

class DiscountSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        Store::query()->get()->each(function (Store $store): void {
            foreach ($this->discounts() as $discount) {
                Discount::withoutGlobalScopes()->updateOrCreate(
                    [
                        'store_id' => $store->getKey(),
                        'code' => $discount['code'],
                    ],
                    [
                        'type' => 'code',
                        'value_type' => $discount['value_type'],
                        'value_amount' => $discount['value_amount'],
                        'starts_at' => now()->subDay(),
                        'ends_at' => now()->addMonth(),
                        'usage_limit' => null,
                        'usage_count' => 0,
                        'rules_json' => $discount['rules_json'],
                        'status' => 'active',
                    ],
                );
            }
        });
    }

    /**
     * @return array<int, array{code: string, value_type: string, value_amount: int, rules_json: array<string, mixed>}>
     */
    private function discounts(): array
    {
        return [
            ['code' => 'SAVE10', 'value_type' => 'percent', 'value_amount' => 10, 'rules_json' => ['customer_eligibility' => 'all']],
            ['code' => '5OFF', 'value_type' => 'fixed', 'value_amount' => 500, 'rules_json' => ['min_purchase_amount' => 2500, 'customer_eligibility' => 'all']],
            ['code' => 'FREESHIP', 'value_type' => 'free_shipping', 'value_amount' => 0, 'rules_json' => ['customer_eligibility' => 'all']],
        ];
    }
}


Output:
Chunk ID: 82d837
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 456
Output:
<?php

namespace Database\Seeders;

use App\Models\Discount;
use App\Models\Store;
use Illuminate\Database\Seeder;

class DiscountSeeder extends Seeder
{
    /**
     * Run the database seeds.
     */
    public function run(): void
    {
        Store::query()->get()->each(function (Store $store): void {
            foreach ($this->discounts() as $discount) {
                Discount::withoutGlobalScopes()->updateOrCreate(
                    [
                        'store_id' => $store->getKey(),
                        'code' => $discount['code'],
                    ],
                    [
                        'type' => 'code',
                        'value_type' => $discount['value_type'],
                        'value_amount' => $discount['value_amount'],
                        'starts_at' => now()->subDay(),
                        'ends_at' => now()->addMonth(),
                        'usage_limit' => null,
                        'usage_count' => 0,
                        'rules_json' => $discount['rules_json'],
                        'status' => 'active',
                    ],
                );
            }
        });
    }

    /**
     * @return array<int, array{code: string, value_type: string, value_amount: int, rules_json: array<string, mixed>}>
     */
    private function discounts(): array
    {
        return [
            ['code' => 'SAVE10', 'value_type' => 'percent', 'value_amount' => 10, 'rules_json' => ['customer_eligibility' => 'all']],
            ['code' => '5OFF', 'value_type' => 'fixed', 'value_amount' => 500, 'rules_json' => ['min_purchase_amount' => 2500, 'customer_eligibility' => 'all']],
            ['code' => 'FREESHIP', 'value_type' => 'free_shipping', 'value_amount' => 0, 'rules_json' => ['customer_eligibility' => 'all']],
        ];
    }
}


rg "WELCOME10|FLAT5|EXPIRED20|MAXED|SAVE10|5OFF" -n specs database tests app resources


rg "WELCOME10|FLAT5|EXPIRED20|MAXED|SAVE10|5OFF" -n specs database tests app resources

rg 'WELCOME10|FLAT5|EXPIRED20|MAXED|SAVE10|5OFF' -n specs database tests app resources

Question: WELCOME10|FLAT5|EXPIRED20|MAXED|SAVE10|5OFF

tests/Feature/Orders/OrderServiceTest.php:217:            'code' => 'SAVE10',
tests/Feature/Orders/OrderServiceTest.php:229:    [$checkout] = orderCompletionCheckout($store, discountCode: 'SAVE10');
tests/Feature/Orders/OrderServiceTest.php:239:                'code' => 'SAVE10',
tests/Feature/Api/StorefrontCheckoutApiTest.php:118:        ->postJson("/api/storefront/v1/checkouts/{$checkoutId}/apply-discount", ['code' => 'SAVE10'])
tests/Feature/Api/StorefrontCheckoutApiTest.php:120:        ->assertJsonPath('data.discount_code', 'SAVE10')
database/seeders/DiscountSeeder.php:45:            ['code' => 'SAVE10', 'value_type' => 'percent', 'value_amount' => 10, 'rules_json' => ['customer_eligibility' => 'all']],
database/seeders/DiscountSeeder.php:46:            ['code' => '5OFF', 'value_type' => 'fixed', 'value_amount' => 500, 'rules_json' => ['min_purchase_amount' => 2500, 'customer_eligibility' => 'all']],
tests/Feature/Checkout/PricingServicesTest.php:135:    Discount::factory()->create(['store_id' => $store->getKey(), 'code' => 'SAVE10']);
tests/Feature/Checkout/PricingServicesTest.php:184:        'code' => 'SAVE10',
tests/Feature/Checkout/PricingServicesTest.php:195:    $checkout->forceFill(['discount_code' => 'SAVE10'])->save();
tests/Feature/Storefront/CartCheckoutUiTest.php:94:        ->set('discountCode', 'SAVE10')
tests/Feature/Storefront/CartCheckoutUiTest.php:97:        ->assertSet('appliedDiscountCode', 'SAVE10')
tests/Feature/Storefront/CartCheckoutUiTest.php:104:    expect(session('cart_discount_code'))->toBe('SAVE10')
tests/Feature/Storefront/CartCheckoutUiTest.php:110:        ->assertSet('discountCode', 'SAVE10');
tests/Feature/Storefront/CartCheckoutUiTest.php:114:    expect($checkout->discount_code)->toBe('SAVE10')
tests/Feature/Storefront/CartCheckoutUiTest.php:167:        ->set('discountCode', 'SAVE10')
tests/Feature/Storefront/CartCheckoutUiTest.php:178:        ->and($checkout->discount_code)->toBe('SAVE10')
specs/02-API-ROUTES.md:778:  "code": "WELCOME10"
specs/02-API-ROUTES.md:792:  "discount_code": "WELCOME10",
specs/02-API-ROUTES.md:803:      "code": "WELCOME10",
specs/02-API-ROUTES.md:1985:          { "code": "WELCOME10", "amount": 500 }
specs/02-API-ROUTES.md:2165:      "code": "WELCOME10",
specs/09-IMPLEMENTATION-ROADMAP.md:1028:| calculates full checkout totals end to end | 2 lines x 2499 = 4998, discount WELCOME10 (10%), shipping flat 499, tax 19% inclusive; pipeline: subtotal 4998 -> discount 499 -> discounted 4499 -> shipping 499 -> tax extracted from gross | total calculation matches expected value | happy path |
specs/09-IMPLEMENTATION-ROADMAP.md:1356:| applies a valid percent discount code at checkout | discount: 10%, code "SAVE10"; apply to checkout with subtotal 5000 | discount = 500 | happy path |
specs/09-IMPLEMENTATION-ROADMAP.md:1357:| applies a valid fixed discount code at checkout | discount: 500 fixed, code "5OFF" | discount = 500 | happy path |
specs/09-IMPLEMENTATION-ROADMAP.md:1545:| creates a percent discount | Livewire: code="SAVE10", type=percent, value=10 | discount in DB | happy path |
specs/09-IMPLEMENTATION-ROADMAP.md:1546:| creates a fixed discount | Livewire: code="5OFF", type=fixed, value=500 | discount in DB | happy path |
specs/09-IMPLEMENTATION-ROADMAP.md:1547:| validates discount code uniqueness within store | create discount with code "SAVE10"; attempt to create another with same code | validation error | validation |
specs/07-SEEDERS-AND-TEST-DATA.md:1441:| WELCOME10 | code | percent | 10 (=10%) | 2025-01-01 | 2027-12-31 | null | 3 | min_purchase_amount: 2000 (=20.00 EUR) | active |
specs/07-SEEDERS-AND-TEST-DATA.md:1442:| FLAT5 | code | fixed | 500 (=5.00 EUR) | 2025-01-01 | 2027-12-31 | null | 0 | (empty) | active |
specs/07-SEEDERS-AND-TEST-DATA.md:1444:| EXPIRED20 | code | percent | 20 (=20%) | 2024-01-01 | 2024-12-31 | null | 0 | (empty) | expired |
specs/07-SEEDERS-AND-TEST-DATA.md:1445:| MAXED | code | percent | 10 (=10%) | 2025-01-01 | 2027-12-31 | 5 | 5 | (empty) | active |
specs/07-SEEDERS-AND-TEST-DATA.md:1448:- WELCOME10: Applies 10% off to orders with subtotal >= 20.00 EUR. Already used 3 times (has capacity remaining since no usage_limit).
specs/07-SEEDERS-AND-TEST-DATA.md:1449:- FLAT5: Applies flat 5.00 EUR discount. Never used.
specs/07-SEEDERS-AND-TEST-DATA.md:1451:- EXPIRED20: Expired - checkout must reject this code with "discount expired" error.
specs/07-SEEDERS-AND-TEST-DATA.md:1452:- MAXED: Usage limit of 5 reached - checkout must reject this code with "discount limit reached" error.
specs/07-SEEDERS-AND-TEST-DATA.md:1840:| Classic Cotton T-Shirt | M / White | 1 | 2499 | 2499 | WELCOME10 discount, amount: 250 |
specs/07-SEEDERS-AND-TEST-DATA.md:1841:| Graphic Print Tee | M | 1 | 2999 | 2999 | WELCOME10 discount, amount: 300 |
specs/07-SEEDERS-AND-TEST-DATA.md:1847:The discount_allocations_json on each order line references the WELCOME10 discount's database ID and the allocated discount amount for that specific line.
specs/07-SEEDERS-AND-TEST-DATA.md:2172:WELCOME10  - 10% off, min order 20.00 EUR (active, usable)
specs/07-SEEDERS-AND-TEST-DATA.md:2173:FLAT5      - 5.00 EUR off (active, usable)
specs/07-SEEDERS-AND-TEST-DATA.md:2175:EXPIRED20  - 20% off (expired, must be rejected)
specs/07-SEEDERS-AND-TEST-DATA.md:2176:MAXED      - 10% off (usage limit reached, must be rejected)
specs/07-SEEDERS-AND-TEST-DATA.md:2245:For orders that use a discount code (e.g. Order #1015 with WELCOME10), each order line's `discount_allocations_json` contains an array of allocation objects. Each allocation references the discount's database ID and the cent amount allocated to that specific line. The total of all allocations across all lines equals the order's `discount_amount`.
specs/08-PLAYWRIGHT-E2E-PLAN.md:100:| **Discounts** | WELCOME10 (10% off, min 20 EUR purchase, active), FLAT5 (5 EUR fixed, active), FREESHIP (free shipping, active), EXPIRED20 (expired end date), MAXED (usage_count >= usage_limit) | 5, 8, 9 |
specs/08-PLAYWRIGHT-E2E-PLAN.md:932:- Page displays "WELCOME10"
specs/08-PLAYWRIGHT-E2E-PLAN.md:933:- Page displays "FLAT5"
specs/08-PLAYWRIGHT-E2E-PLAN.md:1003:**Preconditions:** Logged in as admin, WELCOME10 discount exists
specs/08-PLAYWRIGHT-E2E-PLAN.md:1009:4. Click "WELCOME10" to open the edit form
specs/08-PLAYWRIGHT-E2E-PLAN.md:1030:- Page displays "Expired" status badge (for EXPIRED20)
specs/08-PLAYWRIGHT-E2E-PLAN.md:1447:| WELCOME10 | percent | 10% | 20 EUR | active | Applies 10% discount to subtotal |
specs/08-PLAYWRIGHT-E2E-PLAN.md:1448:| FLAT5 | fixed | 5.00 EUR | none | active | Subtracts 5.00 from subtotal |
specs/08-PLAYWRIGHT-E2E-PLAN.md:1450:| EXPIRED20 | percent | 20% | none | expired (end date in past) | Rejected with "expired" error |
specs/08-PLAYWRIGHT-E2E-PLAN.md:1451:| MAXED | percent | 10% | none | active but usage_count >= usage_limit | Rejected with "usage limit" error |
specs/08-PLAYWRIGHT-E2E-PLAN.md:1552:### Test 8.6: Can apply valid discount code WELCOME10
specs/08-PLAYWRIGHT-E2E-PLAN.md:1554:**Preconditions:** Product #1 in cart (24.99 EUR, above 20 EUR minimum), WELCOME10 discount exists
specs/08-PLAYWRIGHT-E2E-PLAN.md:1563:7. Enter discount code: `WELCOME10` in the discount_code field
specs/08-PLAYWRIGHT-E2E-PLAN.md:1567:- Page displays "WELCOME10" label
specs/08-PLAYWRIGHT-E2E-PLAN.md:1595:**Preconditions:** Product #1 in cart, EXPIRED20 discount exists (expired)
specs/08-PLAYWRIGHT-E2E-PLAN.md:1603:6. Enter discount code: `EXPIRED20` in the discount_code field
specs/08-PLAYWRIGHT-E2E-PLAN.md:1614:**Preconditions:** Product #1 in cart, MAXED discount exists (usage limit reached)
specs/08-PLAYWRIGHT-E2E-PLAN.md:1622:6. Enter discount code: `MAXED` in the discount_code field
specs/08-PLAYWRIGHT-E2E-PLAN.md:1651:### Test 8.11: Can apply FLAT5 discount for fixed amount off
specs/08-PLAYWRIGHT-E2E-PLAN.md:1653:**Preconditions:** Product #1 in cart, FLAT5 discount exists
specs/08-PLAYWRIGHT-E2E-PLAN.md:1661:6. Enter discount code: `FLAT5` in the discount_code field
specs/08-PLAYWRIGHT-E2E-PLAN.md:1665:- Page displays "FLAT5" label
specs/08-PLAYWRIGHT-E2E-PLAN.md:1741:With FLAT5 discount applied:
specs/08-PLAYWRIGHT-E2E-PLAN.md:1746:| Discount (FLAT5) | -5.00 EUR |
specs/08-PLAYWRIGHT-E2E-PLAN.md:1847:**Preconditions:** Product #1, FLAT5 discount, Domestic shipping zone
specs/08-PLAYWRIGHT-E2E-PLAN.md:1855:6. Enter discount code: `FLAT5` in the discount_code field
specs/08-PLAYWRIGHT-E2E-PLAN.md:1857:8. Verify "FLAT5" is displayed
specs/08-PLAYWRIGHT-E2E-PLAN.md:1872:- Page displays "FLAT5" label in checkout totals
resources/views/livewire/storefront/checkout/show.blade.php:153:                                <flux:input wire:model="discountCode" label="Discount code" placeholder="SAVE10" />
resources/views/livewire/storefront/cart/show.blade.php:109:                            <flux:input wire:model="discountCode" label="Discount code" placeholder="SAVE10" />


Output:
Chunk ID: 4d99b8
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 2233
Output:
tests/Feature/Orders/OrderServiceTest.php:217:            'code' => 'SAVE10',
tests/Feature/Orders/OrderServiceTest.php:229:    [$checkout] = orderCompletionCheckout($store, discountCode: 'SAVE10');
tests/Feature/Orders/OrderServiceTest.php:239:                'code' => 'SAVE10',
tests/Feature/Api/StorefrontCheckoutApiTest.php:118:        ->postJson("/api/storefront/v1/checkouts/{$checkoutId}/apply-discount", ['code' => 'SAVE10'])
tests/Feature/Api/StorefrontCheckoutApiTest.php:120:        ->assertJsonPath('data.discount_code', 'SAVE10')
database/seeders/DiscountSeeder.php:45:            ['code' => 'SAVE10', 'value_type' => 'percent', 'value_amount' => 10, 'rules_json' => ['customer_eligibility' => 'all']],
database/seeders/DiscountSeeder.php:46:            ['code' => '5OFF', 'value_type' => 'fixed', 'value_amount' => 500, 'rules_json' => ['min_purchase_amount' => 2500, 'customer_eligibility' => 'all']],
tests/Feature/Checkout/PricingServicesTest.php:135:    Discount::factory()->create(['store_id' => $store->getKey(), 'code' => 'SAVE10']);
tests/Feature/Checkout/PricingServicesTest.php:184:        'code' => 'SAVE10',
tests/Feature/Checkout/PricingServicesTest.php:195:    $checkout->forceFill(['discount_code' => 'SAVE10'])->save();
tests/Feature/Storefront/CartCheckoutUiTest.php:94:        ->set('discountCode', 'SAVE10')
tests/Feature/Storefront/CartCheckoutUiTest.php:97:        ->assertSet('appliedDiscountCode', 'SAVE10')
tests/Feature/Storefront/CartCheckoutUiTest.php:104:    expect(session('cart_discount_code'))->toBe('SAVE10')
tests/Feature/Storefront/CartCheckoutUiTest.php:110:        ->assertSet('discountCode', 'SAVE10');
tests/Feature/Storefront/CartCheckoutUiTest.php:114:    expect($checkout->discount_code)->toBe('SAVE10')
tests/Feature/Storefront/CartCheckoutUiTest.php:167:        ->set('discountCode', 'SAVE10')
tests/Feature/Storefront/CartCheckoutUiTest.php:178:        ->and($checkout->discount_code)->toBe('SAVE10')
specs/02-API-ROUTES.md:778:  "code": "WELCOME10"
specs/02-API-ROUTES.md:792:  "discount_code": "WELCOME10",
specs/02-API-ROUTES.md:803:      "code": "WELCOME10",
specs/02-API-ROUTES.md:1985:          { "code": "WELCOME10", "amount": 500 }
specs/02-API-ROUTES.md:2165:      "code": "WELCOME10",
specs/09-IMPLEMENTATION-ROADMAP.md:1028:| calculates full checkout totals end to end | 2 lines x 2499 = 4998, discount WELCOME10 (10%), shipping flat 499, tax 19% inclusive; pipeline: subtotal 4998 -> discount 499 -> discounted 4499 -> shipping 499 -> tax extracted from gross | total calculation matches expected value | happy path |
specs/09-IMPLEMENTATION-ROADMAP.md:1356:| applies a valid percent discount code at checkout | discount: 10%, code "SAVE10"; apply to checkout with subtotal 5000 | discount = 500 | happy path |
specs/09-IMPLEMENTATION-ROADMAP.md:1357:| applies a valid fixed discount code at checkout | discount: 500 fixed, code "5OFF" | discount = 500 | happy path |
specs/09-IMPLEMENTATION-ROADMAP.md:1545:| creates a percent discount | Livewire: code="SAVE10", type=percent, value=10 | discount in DB | happy path |
specs/09-IMPLEMENTATION-ROADMAP.md:1546:| creates a fixed discount | Livewire: code="5OFF", type=fixed, value=500 | discount in DB | happy path |
specs/09-IMPLEMENTATION-ROADMAP.md:1547:| validates discount code uniqueness within store | create discount with code "SAVE10"; attempt to create another with same code | validation error | validation |
specs/07-SEEDERS-AND-TEST-DATA.md:1441:| WELCOME10 | code | percent | 10 (=10%) | 2025-01-01 | 2027-12-31 | null | 3 | min_purchase_amount: 2000 (=20.00 EUR) | active |
specs/07-SEEDERS-AND-TEST-DATA.md:1442:| FLAT5 | code | fixed | 500 (=5.00 EUR) | 2025-01-01 | 2027-12-31 | null | 0 | (empty) | active |
specs/07-SEEDERS-AND-TEST-DATA.md:1444:| EXPIRED20 | code | percent | 20 (=20%) | 2024-01-01 | 2024-12-31 | null | 0 | (empty) | expired |
specs/07-SEEDERS-AND-TEST-DATA.md:1445:| MAXED | code | percent | 10 (=10%) | 2025-01-01 | 2027-12-31 | 5 | 5 | (empty) | active |
specs/07-SEEDERS-AND-TEST-DATA.md:1448:- WELCOME10: Applies 10% off to orders with subtotal >= 20.00 EUR. Already used 3 times (has capacity remaining since no usage_limit).
specs/07-SEEDERS-AND-TEST-DATA.md:1449:- FLAT5: Applies flat 5.00 EUR discount. Never used.
specs/07-SEEDERS-AND-TEST-DATA.md:1451:- EXPIRED20: Expired - checkout must reject this code with "discount expired" error.
specs/07-SEEDERS-AND-TEST-DATA.md:1452:- MAXED: Usage limit of 5 reached - checkout must reject this code with "discount limit reached" error.
specs/07-SEEDERS-AND-TEST-DATA.md:1840:| Classic Cotton T-Shirt | M / White | 1 | 2499 | 2499 | WELCOME10 discount, amount: 250 |
specs/07-SEEDERS-AND-TEST-DATA.md:1841:| Graphic Print Tee | M | 1 | 2999 | 2999 | WELCOME10 discount, amount: 300 |
specs/07-SEEDERS-AND-TEST-DATA.md:1847:The discount_allocations_json on each order line references the WELCOME10 discount's database ID and the allocated discount amount for that specific line.
specs/07-SEEDERS-AND-TEST-DATA.md:2172:WELCOME10  - 10% off, min order 20.00 EUR (active, usable)
specs/07-SEEDERS-AND-TEST-DATA.md:2173:FLAT5      - 5.00 EUR off (active, usable)
specs/07-SEEDERS-AND-TEST-DATA.md:2175:EXPIRED20  - 20% off (expired, must be rejected)
specs/07-SEEDERS-AND-TEST-DATA.md:2176:MAXED      - 10% off (usage limit reached, must be rejected)
specs/07-SEEDERS-AND-TEST-DATA.md:2245:For orders that use a discount code (e.g. Order #1015 with WELCOME10), each order line's `discount_allocations_json` contains an array of allocation objects. Each allocation references the discount's database ID and the cent amount allocated to that specific line. The total of all allocations across all lines equals the order's `discount_amount`.
specs/08-PLAYWRIGHT-E2E-PLAN.md:100:| **Discounts** | WELCOME10 (10% off, min 20 EUR purchase, active), FLAT5 (5 EUR fixed, active), FREESHIP (free shipping, active), EXPIRED20 (expired end date), MAXED (usage_count >= usage_limit) | 5, 8, 9 |
specs/08-PLAYWRIGHT-E2E-PLAN.md:932:- Page displays "WELCOME10"
specs/08-PLAYWRIGHT-E2E-PLAN.md:933:- Page displays "FLAT5"
specs/08-PLAYWRIGHT-E2E-PLAN.md:1003:**Preconditions:** Logged in as admin, WELCOME10 discount exists
specs/08-PLAYWRIGHT-E2E-PLAN.md:1009:4. Click "WELCOME10" to open the edit form
specs/08-PLAYWRIGHT-E2E-PLAN.md:1030:- Page displays "Expired" status badge (for EXPIRED20)
specs/08-PLAYWRIGHT-E2E-PLAN.md:1447:| WELCOME10 | percent | 10% | 20 EUR | active | Applies 10% discount to subtotal |
specs/08-PLAYWRIGHT-E2E-PLAN.md:1448:| FLAT5 | fixed | 5.00 EUR | none | active | Subtracts 5.00 from subtotal |
specs/08-PLAYWRIGHT-E2E-PLAN.md:1450:| EXPIRED20 | percent | 20% | none | expired (end date in past) | Rejected with "expired" error |
specs/08-PLAYWRIGHT-E2E-PLAN.md:1451:| MAXED | percent | 10% | none | active but usage_count >= usage_limit | Rejected with "usage limit" error |
specs/08-PLAYWRIGHT-E2E-PLAN.md:1552:### Test 8.6: Can apply valid discount code WELCOME10
specs/08-PLAYWRIGHT-E2E-PLAN.md:1554:**Preconditions:** Product #1 in cart (24.99 EUR, above 20 EUR minimum), WELCOME10 discount exists
specs/08-PLAYWRIGHT-E2E-PLAN.md:1563:7. Enter discount code: `WELCOME10` in the discount_code field
specs/08-PLAYWRIGHT-E2E-PLAN.md:1567:- Page displays "WELCOME10" label
specs/08-PLAYWRIGHT-E2E-PLAN.md:1595:**Preconditions:** Product #1 in cart, EXPIRED20 discount exists (expired)
specs/08-PLAYWRIGHT-E2E-PLAN.md:1603:6. Enter discount code: `EXPIRED20` in the discount_code field
specs/08-PLAYWRIGHT-E2E-PLAN.md:1614:**Preconditions:** Product #1 in cart, MAXED discount exists (usage limit reached)
specs/08-PLAYWRIGHT-E2E-PLAN.md:1622:6. Enter discount code: `MAXED` in the discount_code field
specs/08-PLAYWRIGHT-E2E-PLAN.md:1651:### Test 8.11: Can apply FLAT5 discount for fixed amount off
specs/08-PLAYWRIGHT-E2E-PLAN.md:1653:**Preconditions:** Product #1 in cart, FLAT5 discount exists
specs/08-PLAYWRIGHT-E2E-PLAN.md:1661:6. Enter discount code: `FLAT5` in the discount_code field
specs/08-PLAYWRIGHT-E2E-PLAN.md:1665:- Page displays "FLAT5" label
specs/08-PLAYWRIGHT-E2E-PLAN.md:1741:With FLAT5 discount applied:
specs/08-PLAYWRIGHT-E2E-PLAN.md:1746:| Discount (FLAT5) | -5.00 EUR |
specs/08-PLAYWRIGHT-E2E-PLAN.md:1847:**Preconditions:** Product #1, FLAT5 discount, Domestic shipping zone
specs/08-PLAYWRIGHT-E2E-PLAN.md:1855:6. Enter discount code: `FLAT5` in the discount_code field
specs/08-PLAYWRIGHT-E2E-PLAN.md:1857:8. Verify "FLAT5" is displayed
specs/08-PLAYWRIGHT-E2E-PLAN.md:1872:- Page displays "FLAT5" label in checkout totals
resources/views/livewire/storefront/checkout/show.blade.php:153:                                <flux:input wire:model="discountCode" label="Discount code" placeholder="SAVE10" />
resources/views/livewire/storefront/cart/show.blade.php:109:                            <flux:input wire:model="discountCode" label="Discount code" placeholder="SAVE10" />


sed -n '1,220p' tests/Feature/Storefront/CartCheckoutUiTest.php && sed -n '1,260p' app/Services/DiscountService.php


sed -n '1,220p' tests/Feature/Storefront/CartCheckoutUiTest.php && sed -n '1,260p' app/Services/DiscountService.php

DiscountService.php

<?php

use App\Enums\CartStatus;
use App\Enums\CheckoutStatus;
use App\Livewire\Storefront\Account\Auth\Login as CustomerLogin;
use App\Livewire\Storefront\Cart\Show as CartShow;
use App\Livewire\Storefront\Checkout\Show as CheckoutShow;
use App\Livewire\Storefront\Products\Show as ProductShow;
use App\Models\Cart;
use App\Models\Checkout;
use App\Models\Customer;
use App\Models\InventoryItem;
use App\Models\Product;
use App\Models\ProductVariant;
use App\Models\ShippingRate;
use App\Models\Store;
use App\Services\CartService;
use Database\Seeders\DatabaseSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;

uses(RefreshDatabase::class);

beforeEach(function () {
    $this->withoutVite();
    $this->seed(DatabaseSeeder::class);
});

function storefrontUiStore(): Store
{
    $store = Store::query()->where('handle', 'acme-fashion')->firstOrFail();
    app()->instance('current_store', $store);

    return $store;
}

function storefrontUiVariant(Store $store): ProductVariant
{
    $product = Product::withoutGlobalScopes()
        ->where('store_id', $store->getKey())
        ->where('handle', 'classic-cotton-t-shirt')
        ->firstOrFail();

    return ProductVariant::withoutGlobalScopes()
        ->where('product_id', $product->getKey())
        ->oldest('position')
        ->firstOrFail();
}

test('product detail add to cart persists a session cart', function () {
    $store = storefrontUiStore();
    $variant = storefrontUiVariant($store);

    Livewire::test(ProductShow::class, ['handle' => 'classic-cotton-t-shirt'])
        ->set('quantity', 2)
        ->call('addToCart')
        ->assertDispatched('cart-updated');

    $cart = Cart::withoutGlobalScopes()->findOrFail(session('cart_id'));

    expect($cart->store_id)->toBe($store->getKey())
        ->and($cart->lines()->withoutGlobalScopes()->where('variant_id', $variant->getKey())->first()?->quantity)->toBe(2);
});

test('cart page updates and removes line quantities', function () {
    $store = storefrontUiStore();
    $variant = storefrontUiVariant($store);
    $cart = app(CartService::class)->create($store);
    session(['cart_id' => $cart->getKey()]);
    $line = app(CartService::class)->addLine($cart, $variant->getKey(), 2);

    Livewire::test(CartShow::class)
        ->assertSee('Classic Cotton T-Shirt')
        ->call('increaseQuantity', $line->getKey())
        ->assertDispatched('cart-updated');

    expect($line->refresh()->quantity)->toBe(3);

    Livewire::test(CartShow::class)
        ->call('removeLine', $line->getKey())
        ->assertDispatched('cart-updated');

    expect($cart->lines()->withoutGlobalScopes()->count())->toBe(0);
});

test('cart page applies discount estimates shipping and carries discount into checkout', function () {
    $store = storefrontUiStore();
    $variant = storefrontUiVariant($store);
    $cart = app(CartService::class)->create($store);
    session(['cart_id' => $cart->getKey()]);
    app(CartService::class)->addLine($cart, $variant->getKey(), 2);

    $component = Livewire::test(CartShow::class)
        ->set('discountCode', 'SAVE10')
        ->call('applyDiscount')
        ->assertHasNoErrors()
        ->assertSet('appliedDiscountCode', 'SAVE10')
        ->set('shippingCountry', 'DE')
        ->set('shippingPostalCode', '10115')
        ->call('estimateShipping')
        ->assertHasNoErrors()
        ->assertSee('Standard Shipping');

    expect(session('cart_discount_code'))->toBe('SAVE10')
        ->and($component->instance()->discountAmount())->toBe(500)
        ->and($component->instance()->estimatedShippingAmount())->toBe(799)
        ->and($component->instance()->estimatedTotal())->toBe(5297);

    Livewire::test(CheckoutShow::class)
        ->assertSet('discountCode', 'SAVE10');

    $checkout = Checkout::withoutGlobalScopes()->where('cart_id', $cart->getKey())->firstOrFail();

    expect($checkout->discount_code)->toBe('SAVE10')
        ->and($checkout->totals_json['discount'])->toBe(500);
});

test('customer login merges an existing guest cart without creating empty carts', function () {
    $store = storefrontUiStore();
    $variant = storefrontUiVariant($store);
    $customer = Customer::withoutGlobalScopes()
        ->where('store_id', $store->getKey())
        ->where('email', 'customer@acme.test')
        ->firstOrFail();
    $customerCart = app(CartService::class)->create($store, $customer);
    $guestCart = app(CartService::class)->create($store);
    session(['cart_id' => $guestCart->getKey()]);

    app(CartService::class)->addLine($customerCart, $variant->getKey(), 1);
    app(CartService::class)->addLine($guestCart, $variant->getKey(), 2);

    Livewire::test(CustomerLogin::class)
        ->set('email', 'customer@acme.test')
        ->set('password', 'password')
        ->call('login');

    expect($guestCart->refresh()->status)->toBe(CartStatus::Abandoned)
        ->and($customerCart->refresh()->lines()->withoutGlobalScopes()->where('variant_id', $variant->g…6212 chars truncated…    DiscountValueType::Percent => (int) round($qualifyingSubtotal * $discount->value_amount / 100),
            DiscountValueType::Fixed => min($discount->value_amount, $qualifyingSubtotal),
            DiscountValueType::FreeShipping => 0,
        };

        $remaining = $discountAmount;
        $allocations = [];
        $lastIndex = $qualifyingLines->keys()->last();

        foreach ($qualifyingLines as $index => $line) {
            if ($index === $lastIndex) {
                $allocations[$line->getKey()] = $remaining;

                continue;
            }

            $allocation = (int) round($discountAmount * $line->line_total_amount / $qualifyingSubtotal);
            $allocations[$line->getKey()] = $allocation;
            $remaining -= $allocation;
        }

        return new DiscountResult($discountAmount, $allocations);
    }

    public function applyToCart(Cart $cart, Discount $discount): DiscountResult
    {
        return DB::transaction(function () use ($cart, $discount): DiscountResult {
            $lines = $this->cartLines($cart);
            $result = $this->calculate($discount, $lines->sum('line_subtotal_amount'), $lines->all());

            $lines->each(function (CartLine $line) use ($result): void {
                $discountAmount = $result->allocations[$line->getKey()] ?? 0;

                $line->forceFill([
                    'line_discount_amount' => $line->line_discount_amount + $discountAmount,
                    'line_total_amount' => max(0, $line->line_total_amount - $discountAmount),
                ])->save();
            });

            return $result;
        });
    }

    /**
     * @return Collection<int, CartLine>
     */
    private function cartLines(Cart $cart): Collection
    {
        return CartLine::withoutGlobalScopes()
            ->where('cart_id', $cart->getKey())
            ->orderBy('id')
            ->get();
    }

    /**
     * @param  Collection<int, CartLine>  $lines
     * @return Collection<int, CartLine>
     */
    private function qualifyingLines(Discount $discount, Collection $lines): Collection
    {
        $productIds = collect(data_get($discount->rules_json, 'applicable_product_ids', []))
            ->filter()
            ->map(fn (mixed $id): int => (int) $id)
            ->values();
        $collectionIds = collect(data_get($discount->rules_json, 'applicable_collection_ids', []))
            ->filter()
            ->map(fn (mixed $id): int => (int) $id)
            ->values();

        if ($productIds->isEmpty() && $collectionIds->isEmpty()) {
            return $lines;
        }

        return $lines->filter(function (CartLine $line) use ($productIds, $collectionIds): bool {
            $variant = ProductVariant::withoutGlobalScopes()
                ->with(['product' => fn ($query) => $query->withoutGlobalScopes()->with('collections')])
                ->find($line->variant_id);

            if (! $variant instanceof ProductVariant || $variant->product === null) {
                return false;
            }

            if ($productIds->contains((int) $variant->product_id)) {
                return true;
            }

            return $variant->product->collections
                ->pluck('id')
                ->map(fn (int $id): int => $id)
                ->intersect($collectionIds)
                ->isNotEmpty();
        });
    }

    private function onePerCustomer(Discount $discount): bool
    {
        return (bool) data_get($discount->rules_json, 'one_per_customer', false);
    }

    private function customerHasUsedDiscount(Discount $discount, Cart $cart): bool
    {
        if ($cart->customer_id === null) {
            return false;
        }

        $discountCode = $discount->code ? mb_strtolower($discount->code) : null;

        return OrderLine::query()
            ->whereHas('order', function ($query) use ($discount, $cart): void {
                $query
                    ->withoutGlobalScopes()
                    ->where('store_id', $discount->store_id)
                    ->where('customer_id', $cart->customer_id)
                    ->where('discount_amount', '>', 0);
            })
            ->get()
            ->contains(function (OrderLine $line) use ($discount, $discountCode): bool {
                return collect($line->discount_allocations_json ?? [])
                    ->contains(function (mixed $allocation) use ($discount, $discountCode): bool {
                        $allocationDiscountId = data_get($allocation, 'discount_id');

                        if ($allocationDiscountId !== null && (int) $allocationDiscountId === $discount->getKey()) {
                            return true;
                        }

                        if ($discountCode === null) {
                            return false;
                        }

                        return mb_strtolower((string) data_get($allocation, 'code', '')) === $discountCode;
                    });
            });
    }
}


Output:
Chunk ID: bb13d2
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 4053
Output:
<?php

use App\Enums\CartStatus;
use App\Enums\CheckoutStatus;
use App\Livewire\Storefront\Account\Auth\Login as CustomerLogin;
use App\Livewire\Storefront\Cart\Show as CartShow;
use App\Livewire\Storefront\Checkout\Show as CheckoutShow;
use App\Livewire\Storefront\Products\Show as ProductShow;
use App\Models\Cart;
use App\Models\Checkout;
use App\Models\Customer;
use App\Models\InventoryItem;
use App\Models\Product;
use App\Models\ProductVariant;
use App\Models\ShippingRate;
use App\Models\Store;
use App\Services\CartService;
use Database\Seeders\DatabaseSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;

uses(RefreshDatabase::class);

beforeEach(function () {
    $this->withoutVite();
    $this->seed(DatabaseSeeder::class);
});

function storefrontUiStore(): Store
{
    $store = Store::query()->where('handle', 'acme-fashion')->firstOrFail();
    app()->instance('current_store', $store);

    return $store;
}

function storefrontUiVariant(Store $store): ProductVariant
{
    $product = Product::withoutGlobalScopes()
        ->where('store_id', $store->getKey())
        ->where('handle', 'classic-cotton-t-shirt')
        ->firstOrFail();

    return ProductVariant::withoutGlobalScopes()
        ->where('product_id', $product->getKey())
        ->oldest('position')
        ->firstOrFail();
}

test('product detail add to cart persists a session cart', function () {
    $store = storefrontUiStore();
    $variant = storefrontUiVariant($store);

    Livewire::test(ProductShow::class, ['handle' => 'classic-cotton-t-shirt'])
        ->set('quantity', 2)
        ->call('addToCart')
        ->assertDispatched('cart-updated');

    $cart = Cart::withoutGlobalScopes()->findOrFail(session('cart_id'));

    expect($cart->store_id)->toBe($store->getKey())
        ->and($cart->lines()->withoutGlobalScopes()->where('variant_id', $variant->getKey())->first()?->quantity)->toBe(2);
});

test('cart page updates and removes line quantities', function () {
    $store = storefrontUiStore();
    $variant = storefrontUiVariant($store);
    $cart = app(CartService::class)->create($store);
    session(['cart_id' => $cart->getKey()]);
    $line = app(CartService::class)->addLine($cart, $variant->getKey(), 2);

    Livewire::test(CartShow::class)
        ->assertSee('Classic Cotton T-Shirt')
        ->call('increaseQuantity', $line->getKey())
        ->assertDispatched('cart-updated');

    expect($line->refresh()->quantity)->toBe(3);

    Livewire::test(CartShow::class)
        ->call('removeLine', $line->getKey())
        ->assertDispatched('cart-updated');

    expect($cart->lines()->withoutGlobalScopes()->count())->toBe(0);
});

test('cart page applies discount estimates shipping and carries discount into checkout', function () {
    $store = storefrontUiStore();
    $variant = storefrontUiVariant($store);
    $cart = app(CartService::class)->create($store);
    session(['cart_id' => $cart->getKey()]);
    app(CartService::class)->addLine($cart, $variant->getKey(), 2);

    $component = Livewire::test(CartShow::class)
        ->set('discountCode', 'SAVE10')
        ->call('applyDiscount')
        ->assertHasNoErrors()
        ->assertSet('appliedDiscountCode', 'SAVE10')
        ->set('shippingCountry', 'DE')
        ->set('shippingPostalCode', '10115')
        ->call('estimateShipping')
        ->assertHasNoErrors()
        ->assertSee('Standard Shipping');

    expect(session('cart_discount_code'))->toBe('SAVE10')
        ->and($component->instance()->discountAmount())->toBe(500)
        ->and($component->instance()->estimatedShippingAmount())->toBe(799)
        ->and($component->instance()->estimatedTotal())->toBe(5297);

    Livewire::test(CheckoutShow::class)
        ->assertSet('discountCode', 'SAVE10');

    $checkout = Checkout::withoutGlobalScopes()->where('cart_id', $cart->getKey())->firstOrFail();

    expect($checkout->discount_code)->toBe('SAVE10')
        ->and($checkout->totals_json['discount'])->toBe(500);
});

test('customer login merges an existing guest cart without creating empty carts', function () {
    $store = storefrontUiStore();
    $variant = storefrontUiVariant($store);
    $customer = Customer::withoutGlobalScopes()
        ->where('store_id', $store->getKey())
        ->where('email', 'customer@acme.test')
        ->firstOrFail();
    $customerCart = app(CartService::class)->create($store, $customer);
    $guestCart = app(CartService::class)->create($store);
    session(['cart_id' => $guestCart->getKey()]);

    app(CartService::class)->addLine($customerCart, $variant->getKey(), 1);
    app(CartService::class)->addLine($guestCart, $variant->getKey(), 2);

    Livewire::test(CustomerLogin::class)
        ->set('email', 'customer@acme.test')
        ->set('password', 'password')
        ->call('login');

    expect($guestCart->refresh()->status)->toBe(CartStatus::Abandoned)
        ->and($customerCart->refresh()->lines()->withoutGlobalScopes()->where('variant_id', $variant->getKey())->first()?->quantity)->toBe(2)
        ->and(Cart::withoutGlobalScopes()->where('store_id', $store->getKey())->count())->toBe(2);
});

test('checkout page progresses through address shipping discount and payment selection', function () {
    $store = storefrontUiStore();
    $variant = storefrontUiVariant($store);
    $cart = app(CartService::class)->create($store);
    session(['cart_id' => $cart->getKey()]);
    app(CartService::class)->addLine($cart, $variant->getKey(), 2);

    $rate = ShippingRate::withoutGlobalScopes()
        ->whereHas('zone', fn ($query) => $query->withoutGlobalScopes()->where('store_id', $store->getKey()))
        ->where('name', 'Standard Shipping')
        ->firstOrFail();

    Livewire::test(CheckoutShow::class)
        ->set('email', 'buyer@example.test')
        ->set('shippingAddress.first_name', 'Test')
        ->set('shippingAddress.last_name', 'Buyer')
        ->set('shippingAddress.address1', 'Main Street 1')
        ->set('shippingAddress.city', 'Berlin')
        ->set('shippingAddress.country', 'DE')
        ->set('shippingAddress.postal_code', '10115')
        ->call('saveAddress')
        ->assertSet('step', 'shipping')
        ->set('selectedShippingRateId', $rate->getKey())
        ->call('selectShippingMethod')
        ->assertSet('step', 'payment')
        ->set('discountCode', 'SAVE10')
        ->call('applyDiscount')
        ->assertHasNoErrors()
        ->set('paymentMethod', 'credit_card')
        ->call('selectPaymentMethod')
        ->assertSet('step', 'reserved');

    $checkout = Checkout::withoutGlobalScopes()->where('cart_id', $cart->getKey())->firstOrFail();
    $inventory = InventoryItem::withoutGlobalScopes()->where('variant_id', $variant->getKey())->firstOrFail();

    expect($checkout->status)->toBe(CheckoutStatus::PaymentSelected)
        ->and($checkout->discount_code)->toBe('SAVE10')
        ->and($checkout->totals_json['discount'])->toBeGreaterThan(0)
        ->and($inventory->quantity_reserved)->toBe(2);
});
<?php

namespace App\Services;

use App\Enums\DiscountStatus;
use App\Enums\DiscountType;
use App\Enums\DiscountValueType;
use App\Exceptions\InvalidDiscountException;
use App\Models\Cart;
use App\Models\CartLine;
use App\Models\Discount;
use App\Models\OrderLine;
use App\Models\ProductVariant;
use App\Models\Store;
use App\ValueObjects\DiscountResult;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;

class DiscountService
{
    public function validate(string $code, Store $store, Cart $cart): Discount
    {
        $normalizedCode = mb_strtolower(trim($code));

        $discount = Discount::withoutGlobalScopes()
            ->where('store_id', $store->getKey())
            ->where('type', DiscountType::Code)
            ->whereRaw('lower(code) = ?', [$normalizedCode])
            ->first();

        if (! $discount instanceof Discount) {
            throw InvalidDiscountException::because('discount_not_found', 'Discount code was not found.');
        }

        $this->validateDiscountForCart($discount, $cart);

        return $discount;
    }

    /**
     * @return Collection<int, Discount>
     */
    public function automaticForCart(Store $store, Cart $cart): Collection
    {
        return Discount::withoutGlobalScopes()
            ->where('store_id', $store->getKey())
            ->where('type', DiscountType::Automatic->value)
            ->where('status', DiscountStatus::Active->value)
            ->orderBy('id')
            ->get()
            ->filter(function (Discount $discount) use ($cart): bool {
                try {
                    $this->validateDiscountForCart($discount, $cart);

                    return true;
                } catch (InvalidDiscountException) {
                    return false;
                }
            })
            ->values();
    }

    private function validateDiscountForCart(Discount $discount, Cart $cart): void
    {
        if ($discount->status !== DiscountStatus::Active) {
            throw InvalidDiscountException::because('discount_expired', 'Discount is not active.');
        }

        if ($discount->starts_at->isFuture()) {
            throw InvalidDiscountException::because('discount_not_yet_active', 'Discount is not active yet.');
        }

        if ($discount->ends_at !== null && $discount->ends_at->isPast()) {
            throw InvalidDiscountException::because('discount_expired', 'Discount has expired.');
        }

        if ($discount->usage_limit !== null && $discount->usage_count >= $discount->usage_limit) {
            throw InvalidDiscountException::because('discount_usage_limit_reached', 'Discount usage limit has been reached.');
        }

        if ($this->onePerCustomer($discount) && $this->customerHasUsedDiscount($discount, $cart)) {
            throw InvalidDiscountException::because('discount_usage_limit_reached', 'Discount has already been used by this customer.');
        }

        $lines = $this->cartLines($cart);
        $subtotal = $lines->sum('line_subtotal_amount');
        $minimum = (int) data_get($discount->rules_json, 'min_purchase_amount', data_get($discount->rules_json, 'minimum_purchase', 0));

        if ($minimum > 0 && $subtotal < $minimum) {
            throw InvalidDiscountException::because('discount_min_purchase_not_met', 'Cart does not meet the minimum purchase amount.');
        }

        if ($this->qualifyingLines($discount, $lines)->isEmpty()) {
            throw InvalidDiscountException::because('discount_not_applicable', 'Discount does not apply to these cart lines.');
        }
    }

    /**
     * @param  array<int, CartLine>  $lines
     */
    public function calculate(Discount $discount, int $subtotal, array $lines): DiscountResult
    {
        if ($discount->value_type === DiscountValueType::FreeShipping) {
            return new DiscountResult(0, [], true);
        }

        $qualifyingLines = $this->qualifyingLines($discount, collect($lines));
        $qualifyingSubtotal = $qualifyingLines->sum('line_total_amount');

        if ($qualifyingSubtotal <= 0) {
            return new DiscountResult(0, []);
        }

        $discountAmount = match ($discount->value_type) {
            DiscountValueType::Percent => (int) round($qualifyingSubtotal * $discount->value_amount / 100),
            DiscountValueType::Fixed => min($discount->value_amount, $qualifyingSubtotal),
            DiscountValueType::FreeShipping => 0,
        };

        $remaining = $discountAmount;
        $allocations = [];
        $lastIndex = $qualifyingLines->keys()->last();

        foreach ($qualifyingLines as $index => $line) {
            if ($index === $lastIndex) {
                $allocations[$line->getKey()] = $remaining;

                continue;
            }

            $allocation = (int) round($discountAmount * $line->line_total_amount / $qualifyingSubtotal);
            $allocations[$line->getKey()] = $allocation;
            $remaining -= $allocation;
        }

        return new DiscountResult($discountAmount, $allocations);
    }

    public function applyToCart(Cart $cart, Discount $discount): DiscountResult
    {
        return DB::transaction(function () use ($cart, $discount): DiscountResult {
            $lines = $this->cartLines($cart);
            $result = $this->calculate($discount, $lines->sum('line_subtotal_amount'), $lines->all());

            $lines->each(function (CartLine $line) use ($result): void {
                $discountAmount = $result->allocations[$line->getKey()] ?? 0;

                $line->forceFill([
                    'line_discount_amount' => $line->line_discount_amount + $discountAmount,
                    'line_total_amount' => max(0, $line->line_total_amount - $discountAmount),
                ])->save();
            });

            return $result;
        });
    }

    /**
     * @return Collection<int, CartLine>
     */
    private function cartLines(Cart $cart): Collection
    {
        return CartLine::withoutGlobalScopes()
            ->where('cart_id', $cart->getKey())
            ->orderBy('id')
            ->get();
    }

    /**
     * @param  Collection<int, CartLine>  $lines
     * @return Collection<int, CartLine>
     */
    private function qualifyingLines(Discount $discount, Collection $lines): Collection
    {
        $productIds = collect(data_get($discount->rules_json, 'applicable_product_ids', []))
            ->filter()
            ->map(fn (mixed $id): int => (int) $id)
            ->values();
        $collectionIds = collect(data_get($discount->rules_json, 'applicable_collection_ids', []))
            ->filter()
            ->map(fn (mixed $id): int => (int) $id)
            ->values();

        if ($productIds->isEmpty() && $collectionIds->isEmpty()) {
            return $lines;
        }

        return $lines->filter(function (CartLine $line) use ($productIds, $collectionIds): bool {
            $variant = ProductVariant::withoutGlobalScopes()
                ->with(['product' => fn ($query) => $query->withoutGlobalScopes()->with('collections')])
                ->find($line->variant_id);

            if (! $variant instanceof ProductVariant || $variant->product === null) {
                return false;
            }

            if ($productIds->contains((int) $variant->product_id)) {
                return true;
            }

            return $variant->product->collections
                ->pluck('id')
                ->map(fn (int $id): int => $id)
                ->intersect($collectionIds)
                ->isNotEmpty();
        });
    }

    private function onePerCustomer(Discount $discount): bool
    {
        return (bool) data_get($discount->rules_json, 'one_per_customer', false);
    }

    private function customerHasUsedDiscount(Discount $discount, Cart $cart): bool
    {
        if ($cart->customer_id === null) {
            return false;
        }

        $discountCode = $discount->code ? mb_strtolower($discount->code) : null;

        return OrderLine::query()
            ->whereHas('order', function ($query) use ($discount, $cart): void {
                $query
                    ->withoutGlobalScopes()
                    ->where('store_id', $discount->store_id)
                    ->where('customer_id', $cart->customer_id)
                    ->where('discount_amount', '>', 0);
            })
            ->get()
            ->contains(function (OrderLine $line) use ($discount, $discountCode): bool {
                return collect($line->discount_allocations_json ?? [])
                    ->contains(function (mixed $allocation) use ($discount, $discountCode): bool {
                        $allocationDiscountId = data_get($allocation, 'discount_id');

                        if ($allocationDiscountId !== null && (int) $allocationDiscountId === $discount->getKey()) {
                            return true;
                        }

                        if ($discountCode === null) {
                            return false;
                        }

                        return mb_strtolower((string) data_get($allocation, 'code', '')) === $discountCode;
                    });
            });
    }
}


sed -n '1,120p' app/Enums/DiscountStatus.php && sed -n '1,160p' app/Models/Discount.php


sed -n '1,120p' app/Enums/DiscountStatus.php && sed -n '1,160p' app/Models/Discount.php

DiscountStatus.php

<?php

namespace App\Enums;

enum DiscountStatus: string
{
    case Draft = 'draft';
    case Active = 'active';
    case Expired = 'expired';
    case Disabled = 'disabled';
}
<?php

namespace App\Models;

use App\Enums\DiscountStatus;
use App\Enums\DiscountType;
use App\Enums\DiscountValueType;
use App\Models\Concerns\BelongsToStore;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class Discount extends Model
{
    /** @use HasFactory<\Database\Factories\DiscountFactory> */
    use BelongsToStore, HasFactory;

    /**
     * @var list<string>
     */
    protected $fillable = [
        'store_id',
        'type',
        'code',
        'value_type',
        'value_amount',
        'starts_at',
        'ends_at',
        'usage_limit',
        'usage_count',
        'rules_json',
        'status',
    ];

    /**
     * @var array<string, mixed>
     */
    protected $attributes = [
        'type' => 'code',
        'value_amount' => 0,
        'usage_count' => 0,
        'rules_json' => '{}',
        'status' => 'active',
    ];

    /**
     * @return BelongsTo<Store, $this>
     */
    public function store(): BelongsTo
    {
        return $this->belongsTo(Store::class);
    }

    /**
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            'type' => DiscountType::class,
            'value_type' => DiscountValueType::class,
            'value_amount' => 'integer',
            'starts_at' => 'datetime',
            'ends_at' => 'datetime',
            'usage_limit' => 'integer',
            'usage_count' => 'integer',
            'rules_json' => 'array',
            'status' => DiscountStatus::class,
        ];
    }
}


Output:
Chunk ID: be3eec
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 454
Output:
<?php

namespace App\Enums;

enum DiscountStatus: string
{
    case Draft = 'draft';
    case Active = 'active';
    case Expired = 'expired';
    case Disabled = 'disabled';
}
<?php

namespace App\Models;

use App\Enums\DiscountStatus;
use App\Enums\DiscountType;
use App\Enums\DiscountValueType;
use App\Models\Concerns\BelongsToStore;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;

class Discount extends Model
{
    /** @use HasFactory<\Database\Factories\DiscountFactory> */
    use BelongsToStore, HasFactory;

    /**
     * @var list<string>
     */
    protected $fillable = [
        'store_id',
        'type',
        'code',
        'value_type',
        'value_amount',
        'starts_at',
        'ends_at',
        'usage_limit',
        'usage_count',
        'rules_json',
        'status',
    ];

    /**
     * @var array<string, mixed>
     */
    protected $attributes = [
        'type' => 'code',
        'value_amount' => 0,
        'usage_count' => 0,
        'rules_json' => '{}',
        'status' => 'active',
    ];

    /**
     * @return BelongsTo<Store, $this>
     */
    public function store(): BelongsTo
    {
        return $this->belongsTo(Store::class);
    }

    /**
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            'type' => DiscountType::class,
            'value_type' => DiscountValueType::class,
            'value_amount' => 'integer',
            'starts_at' => 'datetime',
            'ends_at' => 'datetime',
            'usage_limit' => 'integer',
            'usage_count' => 'integer',
            'rules_json' => 'array',
            'status' => DiscountStatus::class,
        ];
    }
}


Suite 8 depends on discount fixtures the current seeder only partially provides. I’m going to align the seed data with the spec while keeping the existing `SAVE10` and `5OFF` codes so the earlier feature tests remain valid.


sed -n '1,220p' /Users/fabianwesner/Herd/shop/.agents/skills/laravel-best-practices/SKILL.md


sed -n '1,220p' /Users/fabianwesner/Herd/shop/.agents/skills/laravel-best-practices/SKILL.md

---
name: laravel-best-practices
description: "Apply this skill whenever writing, reviewing, or refactoring Laravel PHP code. This includes creating or modifying controllers, models, migrations, form requests, policies, jobs, scheduled commands, service classes, and Eloquent queries. Triggers for N+1 and query performance issues, caching strategies, authorization and security patterns, validation, error handling, queue and job configuration, route definitions, and architectural decisions. Also use for Laravel code reviews and refactoring existing Laravel code to follow best practices. Covers any task involving Laravel backend PHP code patterns."
license: MIT
metadata:
  author: laravel
---

# Laravel Best Practices

Best practices for Laravel, prioritized by impact. Each rule teaches what to do and why. For exact API syntax, verify with `search-docs`.

## Consistency First

Before applying any rule, check what the application already does. Laravel offers multiple valid approaches — the best choice is the one the codebase already uses, even if another pattern would be theoretically better. Inconsistency is worse than a suboptimal pattern.

Check sibling files, related controllers, models, or tests for established patterns. If one exists, follow it — don't introduce a second way. These rules are defaults for when no pattern exists yet, not overrides.

## Quick Reference

### 1. Database Performance → `rules/db-performance.md`

- Eager load with `with()` to prevent N+1 queries
- Enable `Model::preventLazyLoading()` in development
- Select only needed columns, avoid `SELECT *`
- `chunk()` / `chunkById()` for large datasets
- Index columns used in `WHERE`, `ORDER BY`, `JOIN`
- `withCount()` instead of loading relations to count
- `cursor()` for memory-efficient read-only iteration
- Never query in Blade templates

### 2. Advanced Query Patterns → `rules/advanced-queries.md`

- `addSelect()` subqueries over eager-loading entire has-many for a single value
- Dynamic relationships via subquery FK + `belongsTo`
- Conditional aggregates (`CASE WHEN` in `selectRaw`) over multiple count queries
- `setRelation()` to prevent circular N+1 queries
- `whereIn` + `pluck()` over `whereHas` for better index usage
- Two simple queries can beat one complex query
- Compound indexes matching `orderBy` column order
- Correlated subqueries in `orderBy` for has-many sorting (avoid joins)

### 3. Security → `rules/security.md`

- Define `$fillable` or `$guarded` on every model, authorize every action via policies or gates
- No raw SQL with user input — use Eloquent or query builder
- `{{ }}` for output escaping, `@csrf` on all POST/PUT/DELETE forms, `throttle` on auth and API routes
- Validate MIME type, extension, and size for file uploads
- Never commit `.env`, use `config()` for secrets, `encrypted` cast for sensitive DB fields

### 4. Caching → `rules/caching.md`

- `Cache::remember()` over manual get/put
- `Cache::flexible()` for stale-while-revalidate on high-traffic data
- `Cache::memo()` to avoid redundant cache hits within a request
- Cache tags to invalidate related groups
- `Cache::add()` for atomic conditional writes
- `once()` to memoize per-request or per-object lifetime
- `Cache::lock()` / `lockForUpdate()` for race conditions
- Failover cache stores in production

### 5. Eloquent Patterns → `rules/eloquent.md`

- Correct relationship types with return type hints
- Local scopes for reusable query constraints
- Global scopes sparingly — document their existence
- Attribute casts in the `casts()` method
- Cast date columns, use Carbon instances in templates
- `whereBelongsTo($model)` for cleaner queries
- Never hardcode table names — use `(new Model)->getTable()` or Eloquent queries

### 6. Validation & Forms → `rules/validation.md`

- Form Request classes, not inline validation
- Array notation `['required', 'email']` for new code; follow existing convention
- `$request->validated()` only — never `$request->all()`
- `Rule::when()` for conditional validation
- `after()` instead of `withValidator()`

### 7. Configuration → `rules/config.md`

- `env()` only inside config files
- `App::environment()` or `app()->isProduction()`
- Config, lang files, and constants over hardcoded text

### 8. Testing Patterns → `rules/testing.md`

- `LazilyRefreshDatabase` over `RefreshDatabase` for speed
- `assertModelExists()` over raw `assertDatabaseHas()`
- Factory states and sequences over manual overrides
- Use fakes (`Event::fake()`, `Exceptions::fake()`, etc.) — but always after factory setup, not before
- `recycle()` to share relationship instances across factories

### 9. Queue & Job Patterns → `rules/queue-jobs.md`

- `retry_after` must exceed job `timeout`; use exponential backoff `[1, 5, 10]`
- `ShouldBeUnique` to prevent duplicates; `ShouldBeUniqueUntilProcessing` for early lock release
- Always implement `failed()`; with `retryUntil()`, set `$tries = 0`
- `RateLimited` middleware for external API calls; `Bus::batch()` for related jobs
- Horizon for complex multi-queue scenarios

### 10. Routing & Controllers → `rules/routing.md`

- Implicit route model binding
- Scoped bindings for nested resources
- `Route::resource()` or `apiResource()`
- Methods under 10 lines — extract to actions/services
- Type-hint Form Requests for auto-validation

### 11. HTTP Client → `rules/http-client.md`

- Explicit `timeout` and `connectTimeout` on every request
- `retry()` with exponential backoff for external APIs
- Check response status or use `throw()`
- `Http::pool()` for concurrent independent requests
- `Http::fake()` and `preventStrayRequests()` in tests

### 12. Events, Notifications & Mail → `rules/events-notifications.md`, `rules/mail.md`

- Event discovery over manual registration; `event:cache` in production
- `ShouldDispatchAfterCommit` / `afterCommit()` inside transactions
- Queue notifications and mailables with `ShouldQueue`
- On-demand notifications for non-user recipients
- `HasLocalePreference` on notifiable models
- `assertQueued()` not `assertSent()` for queued mailables
- Markdown mailables for transactional emails

### 13. Error Handling → `rules/error-handling.md`

- `report()`/`render()` on exception classes or in `bootstrap/app.php` — follow existing pattern
- `ShouldntReport` for exceptions that should never log
- Throttle high-volume exceptions to protect log sinks
- `dontReportDuplicates()` for multi-catch scenarios
- Force JSON rendering for API routes
- Structured context via `context()` on exception classes

### 14. Task Scheduling → `rules/scheduling.md`

- `withoutOverlapping()` on variable-duration tasks
- `onOneServer()` on multi-server deployments
- `runInBackground()` for concurrent long tasks
- `environments()` to restrict to appropriate environments
- `takeUntilTimeout()` for time-bounded processing
- Schedule groups for shared configuration

### 15. Architecture → `rules/architecture.md`

- Single-purpose Action classes; dependency injection over `app()` helper
- Prefer official Laravel packages and follow conventions, don't override defaults
- Default to `ORDER BY id DESC` or `created_at DESC`; `mb_*` for UTF-8 safety
- `defer()` for post-response work; `Context` for request-scoped data; `Concurrency::run()` for parallel execution

### 16. Migrations → `rules/migrations.md`

- Generate migrations with `php artisan make:migration`
- `constrained()` for foreign keys
- Never modify migrations that have run in production
- Add indexes in the migration, not as an afterthought
- Mirror column defaults in model `$attributes`
- Reversible `down()` by default; forward-fix migrations for intentionally irreversible changes
- One concern per migration — never mix DDL and DML

### 17. Collections → `rules/collections.md`

- Higher-order messages for simple collection operations
- `cursor()` vs. `lazy()` — choose based on relationship needs
- `lazyById()` when updating records while iterating
- `toQuery()` for bulk operations on collections

### 18. Blade & Views → `rules/blade-views.md`

- `$attributes->merge()` in component templates
- Blade components over `@include`; `@pushOnce` for per-component scripts
- View Composers for shared view data
- `@aware` for deeply nested component props

### 19. Conventions & Style → `rules/style.md`

- Follow Laravel naming conventions for all entities
- Prefer Laravel helpers (`Str`, `Arr`, `Number`, `Uri`, `Str::of()`, `$request->string()`) over raw PHP functions
- No JS/CSS in Blade, no HTML in PHP classes
- Code should be readable; comments only for config files

## How to Apply

Always use a sub-agent to read rule files and explore this skill's content.

1. Identify the file type and select relevant sections (e.g., migration → §16, controller → §1, §3, §5, §6, §10)
2. Check sibling files for existing patterns — follow those first per Consistency First
3. Verify API syntax with `search-docs` for the installed Laravel version