sed -n '1,320p' app/Services/DiscountService.php

<?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\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.');
        }

        $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();
        });
    }
}


sed -n '1,460p' app/Livewire/Admin/Discounts/Form.php

Form.php

<?php

namespace App\Livewire\Admin\Discounts;

use App\Enums\DiscountStatus;
use App\Enums\DiscountType;
use App\Enums\DiscountValueType;
use App\Models\Collection as ProductCollection;
use App\Models\Discount;
use App\Models\Product;
use App\Models\Store;
use App\Support\Money;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Support\Collection as SupportCollection;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;
use Livewire\Component;

class Form extends Component
{
    use AuthorizesRequests;

    public ?Discount $discount = null;

    public string $type = 'code';

    public string $code = '';

    public string $valueType = 'percent';

    public string $valueAmount = '10';

    public string $minimumPurchaseAmount = '';

    /**
     * @var array<int, int>
     */
    public array $specificProductIds = [];

    /**
     * @var array<int, int>
     */
    public array $specificCollectionIds = [];

    public string $usageLimit = '';

    public bool $onePerCustomer = false;

    public string $startsAt = '';

    public string $endsAt = '';

    public bool $isActive = false;

    public string $productSearch = '';

    public string $collectionSearch = '';

    public string $storeCurrency = 'EUR';

    public function mount(?Discount $discount = null): void
    {
        $store = app('current_store');

        abort_unless($store instanceof Store, 404);

        $this->storeCurrency = $store->default_currency;

        if ($discount?->exists) {
            abort_unless((int) $discount->store_id === $store->getKey(), 404);

            $this->authorize('update', $discount);

            $this->discount = $discount;
            $this->fillFromDiscount($discount);

            return;
        }

        $this->authorize('create', Discount::class);

        $this->startsAt = now()->format('Y-m-d\TH:i');
    }

    public function save(): void
    {
        $store = app('current_store');

        abort_unless($store instanceof Store, 404);

        $this->authorizeSave();
        $this->normalizeCode();

        $this->validate([
            'type' => ['required', Rule::in(['code', 'automatic'])],
            'code' => [
                Rule::requiredIf($this->type === 'code'),
                'nullable',
                'string',
                'max:255',
                function (string $attribute, mixed $value, \Closure $fail) use ($store): void {
                    if ($value === null || trim((string) $value) === '') {
                        return;
                    }

                    $exists = Discount::withoutGlobalScopes()
                        ->where('store_id', $store->getKey())
                        ->whereRaw('lower(code) = ?', [Str::lower(trim((string) $value))])
                        ->when($this->discount instanceof Discount, fn ($query) => $query->where('id', '!=', $this->discount?->getKey()))
                        ->exists();

                    if ($exists) {
                        $fail(__('The discount code has already been taken.'));
                    }
                },
            ],
            'valueType' => ['required', Rule::in(['percent', 'fixed', 'free_shipping'])],
            'valueAmount' => $this->valueAmountRules(),
            'minimumPurchaseAmount' => ['nullable', 'numeric', 'min:0'],
            'usageLimit' => ['nullable', 'integer', 'min:1'],
            'startsAt' => ['required', 'date'],
            'endsAt' => ['nullable', 'date', 'after:startsAt'],
            'onePerCustomer' => ['boolean'],
            'isActive' => ['boolean'],
        ], [], [
            'valueAmount' => 'value amount',
        ]);

        $discount = $this->discount instanceof Discount
            ? tap($this->discount)->update($this->payload($store))
            : Discount::withoutGlobalScopes()->create($this->payload($store));

        $this->discount = $discount->refresh();
        $this->fillFromDiscount($this->discount);

        session()->flash('status', 'Discount saved');
        $this->dispatch('toast', type: 'success', message: __('Discount saved'));
    }

    public function generateCode(): void
    {
        do {
            $code = Str::upper(Str::random(8));
        } while (Discount::withoutGlobalScopes()
            ->where('store_id', $this->storeId())
            ->where('code', $code)
            ->exists());

        $this->code = $code;
    }

    public function addProduct(int $productId): void
    {
        abort_unless($this->productBelongsToStore($productId), 404);

        $this->specificProductIds = collect([...$this->specificProductIds, $productId])
            ->unique()
            ->values()
            ->all();
        $this->productSearch = '';
    }

    public function removeProduct(int $productId): void
    {
        $this->specificProductIds = array_values(array_filter(
            $this->specificProductIds,
            fn (int $selectedProductId): bool => $selectedProductId !== $productId…3380 chars truncated…(data_get($discount->rules_json, 'applicable_product_ids', []))
            ->map(fn (mixed $id): int => (int) $id)
            ->all();
        $this->specificCollectionIds = collect(data_get($discount->rules_json, 'applicable_collection_ids', []))
            ->map(fn (mixed $id): int => (int) $id)
            ->all();
        $this->usageLimit = $discount->usage_limit !== null ? (string) $discount->usage_limit : '';
        $this->onePerCustomer = (bool) data_get($discount->rules_json, 'one_per_customer', false);
        $this->startsAt = $discount->starts_at->format('Y-m-d\TH:i');
        $this->endsAt = $discount->ends_at?->format('Y-m-d\TH:i') ?? '';
        $this->isActive = $discount->status !== DiscountStatus::Disabled;
    }

    /**
     * @return array<string, mixed>
     */
    private function payload(Store $store): array
    {
        return [
            'store_id' => $store->getKey(),
            'type' => DiscountType::from($this->type),
            'code' => $this->type === 'code' ? Str::upper(trim($this->code)) : null,
            'value_type' => DiscountValueType::from($this->valueType),
            'value_amount' => $this->normalizedValueAmount(),
            'starts_at' => $this->startsAt,
            'ends_at' => $this->endsAt !== '' ? $this->endsAt : null,
            'usage_limit' => $this->usageLimit !== '' ? (int) $this->usageLimit : null,
            'rules_json' => $this->rulesPayload(),
            'status' => $this->statusForPayload(),
        ];
    }

    /**
     * @return array<string, mixed>
     */
    private function rulesPayload(): array
    {
        return [
            'min_purchase_amount' => $this->minimumPurchaseAmount !== '' ? Money::fromDecimalString($this->minimumPurchaseAmount) : 0,
            'applicable_product_ids' => $this->validProductIds(),
            'applicable_collection_ids' => $this->validCollectionIds(),
            'one_per_customer' => $this->onePerCustomer,
            'customer_eligibility' => 'all',
        ];
    }

    private function normalizedValueAmount(): int
    {
        return match ($this->valueType) {
            'fixed' => Money::fromDecimalString($this->valueAmount),
            'free_shipping' => 0,
            default => (int) round((float) $this->valueAmount),
        };
    }

    /**
     * @return array<int, int>
     */
    private function validProductIds(): array
    {
        return Product::withoutGlobalScopes()
            ->where('store_id', $this->storeId())
            ->whereKey($this->specificProductIds)
            ->pluck('id')
            ->map(fn (int $id): int => $id)
            ->all();
    }

    /**
     * @return array<int, int>
     */
    private function validCollectionIds(): array
    {
        return ProductCollection::withoutGlobalScopes()
            ->where('store_id', $this->storeId())
            ->whereKey($this->specificCollectionIds)
            ->pluck('id')
            ->map(fn (int $id): int => $id)
            ->all();
    }

    private function productBelongsToStore(int $productId): bool
    {
        return Product::withoutGlobalScopes()
            ->where('store_id', $this->storeId())
            ->whereKey($productId)
            ->exists();
    }

    private function collectionBelongsToStore(int $collectionId): bool
    {
        return ProductCollection::withoutGlobalScopes()
            ->where('store_id', $this->storeId())
            ->whereKey($collectionId)
            ->exists();
    }

    private function storeId(): int
    {
        $store = app('current_store');

        abort_unless($store instanceof Store, 404);

        return $store->getKey();
    }

    private function authorizeSave(): void
    {
        if ($this->discount instanceof Discount) {
            $this->authorize('update', $this->discount);

            return;
        }

        $this->authorize('create', Discount::class);
    }

    private function normalizeCode(): void
    {
        if ($this->type !== DiscountType::Code->value) {
            $this->code = '';

            return;
        }

        $this->code = Str::upper(trim($this->code));
    }

    /**
     * @return list<mixed>
     */
    private function valueAmountRules(): array
    {
        return match ($this->valueType) {
            DiscountValueType::Percent->value => ['required', 'integer', 'min:1', 'max:100'],
            DiscountValueType::FreeShipping->value => ['nullable'],
            default => ['required', 'numeric', 'min:0.01'],
        };
    }

    private function statusForPayload(): DiscountStatus
    {
        if ($this->discount?->status === DiscountStatus::Expired) {
            return DiscountStatus::Expired;
        }

        if ($this->isActive) {
            return DiscountStatus::Active;
        }

        if ($this->discount?->status === DiscountStatus::Draft || ! $this->discount instanceof Discount) {
            return DiscountStatus::Draft;
        }

        return DiscountStatus::Disabled;
    }
}


Output:
Chunk ID: 8db54c
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 1357
Output:
<?php

namespace App\Services;

use App\Exceptions\InvalidCheckoutTransitionException;
use App\Models\CartLine;
use App\Models\Checkout;
use App\Models\ShippingRate;
use App\Models\TaxSettings;
use App\ValueObjects\DiscountResult;
use App\ValueObjects\PricingResult;
use Illuminate\Support\Facades\DB;

class PricingEngine
{
    public function __construct(
        private readonly DiscountService $discounts,
        private readonly ShippingCalculator $shipping,
        private readonly TaxCalculator $taxes,
    ) {}

    public function calculate(Checkout $checkout): PricingResult
    {
        return DB::transaction(function () use ($checkout): PricingResult {
            $checkout = Checkout::withoutGlobalScopes()
                ->with(['cart.lines'])
                ->whereKey($checkout->getKey())
                ->firstOrFail();
            $cart = $checkout->cart;

            $this->resetLineAmounts($checkout);

            $lines = CartLine::withoutGlobalScopes()
                ->where('cart_id', $cart->getKey())
                ->orderBy('id')
                ->get();
            $subtotal = $lines->sum('line_subtotal_amount');
            $discountAmount = 0;
            $freeShipping = false;

            if ($checkout->discount_code) {
                $discount = $this->discounts->validate($checkout->discount_code, $checkout->store, $cart);
                $discountResult = $this->discounts->applyToCart($cart, $discount);
                $discountAmount += $discountResult->amount;
                $freeShipping = $freeShipping || $discountResult->freeShipping;
            }

            foreach ($this->discounts->automaticForCart($checkout->store, $cart) as $discount) {
                $discountResult = $this->discounts->applyToCart($cart, $discount);
                $discountAmount += $discountResult->amount;
                $freeShipping = $freeShipping || $discountResult->freeShipping;
            }

            $lines = CartLine::withoutGlobalScopes()
                ->where('cart_id', $cart->getKey())
                ->orderBy('id')
                ->get();
            $discountResult = new DiscountResult($discountAmount, [], $freeShipping);
            $shippingAmount = $this->shippingAmount($checkout, $discountResult);
            $taxSettings = $this->taxSettings($checkout);
            $taxResult = $this->taxes->calculateForAmounts(
                $lines->pluck('line_total_amount')->map(fn (int $amount): int => $amount)->all(),
                $shippingAmount,
                $taxSettings,
                $checkout->shipping_address_json ?? [],
            );
            $discountedSubtotal = $subtotal - $discountResult->amount;
            $total = $taxSettings->prices_include_tax
                ? $discountedSubtotal + $shippingAmount
                : $discountedSubtotal + $shippingAmount + $taxResult->totalAmount;

            $result = new PricingResult(
                subtotal: $subtotal,
                discount: $discountResult->amount,
                shipping: $shippingAmount,
                taxLines: $taxResult->taxLines,
                taxTotal: $taxResult->totalAmount,
                total: $total,
                currency: $cart->currency,
            );

            $checkout->forceFill([
                'tax_provider_snapshot_json' => $taxResult->toArray(),
                'totals_json' => $result->toArray(),
            ])->save();

            return $result;
        });
    }

    private function resetLineAmounts(Checkout $checkout): void
    {
        CartLine::withoutGlobalScopes()
            ->where('cart_id', $checkout->cart_id)
            ->get()
            ->each(function (CartLine $line): void {
                $subtotal = $line->unit_price_amount * $line->quantity;

                $line->forceFill([
                    'line_subtotal_amount' => $subtotal,
                    'line_discount_amount' => 0,
                    'line_total_amount' => $subtotal,
                ])->save();
            });
    }

    private function shippingAmount(Checkout $checkout, DiscountResult $discountResult): int
    {
        if (! $this->shipping->requiresShipping($checkout->cart)) {
            return 0;
        }

        if ($checkout->shipping_method_id === null) {
            return 0;
        }

        $rate = ShippingRate::withoutGlobalScopes()->find($checkout->shipping_method_id);

        if (! $rate instanceof ShippingRate) {
            throw InvalidCheckoutTransitionException::because('Shipping rate is not available.');
        }

        $amount = $this->shipping->calculate($rate, $checkout->cart);

        if ($amount === null) {
            throw InvalidCheckoutTransitionException::because('Shipping rate is not available for this cart.');
        }

        return $discountResult->freeShipping ? 0 : $amount;
    }

    private function taxSettings(Checkout $checkout): TaxSettings
    {
        return TaxSettings::withoutGlobalScopes()
            ->where('store_id', $checkout->store_id)
            ->first() ?? new TaxSettings([
                'store_id' => $checkout->store_id,
                'mode' => 'manual',
                'provider' => 'none',
                'prices_include_tax' => false,
                'config_json' => [
                    'default_rate_bps' => 0,
                    'shipping_taxable' => false,
                ],
            ]);
    }
}


Output:
Chunk ID: 8fcfc8
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 1828
Output:
<?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\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.');
        }

        $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();
        });
    }
}


Output:
Chunk ID: 98b238
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 3345
Output:
<?php

namespace App\Livewire\Admin\Discounts;

use App\Enums\DiscountStatus;
use App\Enums\DiscountType;
use App\Enums\DiscountValueType;
use App\Models\Collection as ProductCollection;
use App\Models\Discount;
use App\Models\Product;
use App\Models\Store;
use App\Support\Money;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Support\Collection as SupportCollection;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;
use Livewire\Component;

class Form extends Component
{
    use AuthorizesRequests;

    public ?Discount $discount = null;

    public string $type = 'code';

    public string $code = '';

    public string $valueType = 'percent';

    public string $valueAmount = '10';

    public string $minimumPurchaseAmount = '';

    /**
     * @var array<int, int>
     */
    public array $specificProductIds = [];

    /**
     * @var array<int, int>
     */
    public array $specificCollectionIds = [];

    public string $usageLimit = '';

    public bool $onePerCustomer = false;

    public string $startsAt = '';

    public string $endsAt = '';

    public bool $isActive = false;

    public string $productSearch = '';

    public string $collectionSearch = '';

    public string $storeCurrency = 'EUR';

    public function mount(?Discount $discount = null): void
    {
        $store = app('current_store');

        abort_unless($store instanceof Store, 404);

        $this->storeCurrency = $store->default_currency;

        if ($discount?->exists) {
            abort_unless((int) $discount->store_id === $store->getKey(), 404);

            $this->authorize('update', $discount);

            $this->discount = $discount;
            $this->fillFromDiscount($discount);

            return;
        }

        $this->authorize('create', Discount::class);

        $this->startsAt = now()->format('Y-m-d\TH:i');
    }

    public function save(): void
    {
        $store = app('current_store');

        abort_unless($store instanceof Store, 404);

        $this->authorizeSave();
        $this->normalizeCode();

        $this->validate([
            'type' => ['required', Rule::in(['code', 'automatic'])],
            'code' => [
                Rule::requiredIf($this->type === 'code'),
                'nullable',
                'string',
                'max:255',
                function (string $attribute, mixed $value, \Closure $fail) use ($store): void {
                    if ($value === null || trim((string) $value) === '') {
                        return;
                    }

                    $exists = Discount::withoutGlobalScopes()
                        ->where('store_id', $store->getKey())
                        ->whereRaw('lower(code) = ?', [Str::lower(trim((string) $value))])
                        ->when($this->discount instanceof Discount, fn ($query) => $query->where('id', '!=', $this->discount?->getKey()))
                        ->exists();

                    if ($exists) {
                        $fail(__('The discount code has already been taken.'));
                    }
                },
            ],
            'valueType' => ['required', Rule::in(['percent', 'fixed', 'free_shipping'])],
            'valueAmount' => $this->valueAmountRules(),
            'minimumPurchaseAmount' => ['nullable', 'numeric', 'min:0'],
            'usageLimit' => ['nullable', 'integer', 'min:1'],
            'startsAt' => ['required', 'date'],
            'endsAt' => ['nullable', 'date', 'after:startsAt'],
            'onePerCustomer' => ['boolean'],
            'isActive' => ['boolean'],
        ], [], [
            'valueAmount' => 'value amount',
        ]);

        $discount = $this->discount instanceof Discount
            ? tap($this->discount)->update($this->payload($store))
            : Discount::withoutGlobalScopes()->create($this->payload($store));

        $this->discount = $discount->refresh();
        $this->fillFromDiscount($this->discount);

        session()->flash('status', 'Discount saved');
        $this->dispatch('toast', type: 'success', message: __('Discount saved'));
    }

    public function generateCode(): void
    {
        do {
            $code = Str::upper(Str::random(8));
        } while (Discount::withoutGlobalScopes()
            ->where('store_id', $this->storeId())
            ->where('code', $code)
            ->exists());

        $this->code = $code;
    }

    public function addProduct(int $productId): void
    {
        abort_unless($this->productBelongsToStore($productId), 404);

        $this->specificProductIds = collect([...$this->specificProductIds, $productId])
            ->unique()
            ->values()
            ->all();
        $this->productSearch = '';
    }

    public function removeProduct(int $productId): void
    {
        $this->specificProductIds = array_values(array_filter(
            $this->specificProductIds,
            fn (int $selectedProductId): bool => $selectedProductId !== $productId,
        ));
    }

    public function addCollection(int $collectionId): void
    {
        abort_unless($this->collectionBelongsToStore($collectionId), 404);

        $this->specificCollectionIds = collect([...$this->specificCollectionIds, $collectionId])
            ->unique()
            ->values()
            ->all();
        $this->collectionSearch = '';
    }

    public function removeCollection(int $collectionId): void
    {
        $this->specificCollectionIds = array_values(array_filter(
            $this->specificCollectionIds,
            fn (int $selectedCollectionId): bool => $selectedCollectionId !== $collectionId,
        ));
    }

    public function productResults(): SupportCollection
    {
        if (trim($this->productSearch) === '') {
            return collect();
        }

        return Product::withoutGlobalScopes()
            ->where('store_id', $this->storeId())
            ->whereNotIn('id', $this->specificProductIds)
            ->where('title', 'like', '%'.$this->productSearch.'%')
            ->orderBy('title')
            ->limit(5)
            ->get();
    }

    public function collectionResults(): SupportCollection
    {
        if (trim($this->collectionSearch) === '') {
            return collect();
        }

        return ProductCollection::withoutGlobalScopes()
            ->where('store_id', $this->storeId())
            ->whereNotIn('id', $this->specificCollectionIds)
            ->where('title', 'like', '%'.$this->collectionSearch.'%')
            ->orderBy('title')
            ->limit(5)
            ->get();
    }

    public function selectedProducts(): SupportCollection
    {
        return Product::withoutGlobalScopes()
            ->where('store_id', $this->storeId())
            ->whereKey($this->specificProductIds)
            ->orderBy('title')
            ->get();
    }

    public function selectedCollections(): SupportCollection
    {
        return ProductCollection::withoutGlobalScopes()
            ->where('store_id', $this->storeId())
            ->whereKey($this->specificCollectionIds)
            ->orderBy('title')
            ->get();
    }

    public function render(): mixed
    {
        return view('livewire.admin.discounts.form', [
            'isEditing' => $this->discount instanceof Discount,
            'productResults' => $this->productResults(),
            'collectionResults' => $this->collectionResults(),
            'selectedProducts' => $this->selectedProducts(),
            'selectedCollections' => $this->selectedCollections(),
        ])->layout('layouts.app', [
            'title' => $this->discount ? __('Edit discount') : __('Create discount'),
        ]);
    }

    private function fillFromDiscount(Discount $discount): void
    {
        $this->type = $discount->type->value;
        $this->code = (string) $discount->code;
        $this->valueType = $discount->value_type->value;
        $this->valueAmount = $discount->value_type === DiscountValueType::Fixed
            ? number_format($discount->value_amount / 100, 2, '.', '')
            : (string) $discount->value_amount;
        $this->minimumPurchaseAmount = data_get($discount->rules_json, 'min_purchase_amount')
            ? number_format(((int) data_get($discount->rules_json, 'min_purchase_amount')) / 100, 2, '.', '')
            : '';
        $this->specificProductIds = collect(data_get($discount->rules_json, 'applicable_product_ids', []))
            ->map(fn (mixed $id): int => (int) $id)
            ->all();
        $this->specificCollectionIds = collect(data_get($discount->rules_json, 'applicable_collection_ids', []))
            ->map(fn (mixed $id): int => (int) $id)
            ->all();
        $this->usageLimit = $discount->usage_limit !== null ? (string) $discount->usage_limit : '';
        $this->onePerCustomer = (bool) data_get($discount->rules_json, 'one_per_customer', false);
        $this->startsAt = $discount->starts_at->format('Y-m-d\TH:i');
        $this->endsAt = $discount->ends_at?->format('Y-m-d\TH:i') ?? '';
        $this->isActive = $discount->status !== DiscountStatus::Disabled;
    }

    /**
     * @return array<string, mixed>
     */
    private function payload(Store $store): array
    {
        return [
            'store_id' => $store->getKey(),
            'type' => DiscountType::from($this->type),
            'code' => $this->type === 'code' ? Str::upper(trim($this->code)) : null,
            'value_type' => DiscountValueType::from($this->valueType),
            'value_amount' => $this->normalizedValueAmount(),
            'starts_at' => $this->startsAt,
            'ends_at' => $this->endsAt !== '' ? $this->endsAt : null,
            'usage_limit' => $this->usageLimit !== '' ? (int) $this->usageLimit : null,
            'rules_json' => $this->rulesPayload(),
            'status' => $this->statusForPayload(),
        ];
    }

    /**
     * @return array<string, mixed>
     */
    private function rulesPayload(): array
    {
        return [
            'min_purchase_amount' => $this->minimumPurchaseAmount !== '' ? Money::fromDecimalString($this->minimumPurchaseAmount) : 0,
            'applicable_product_ids' => $this->validProductIds(),
            'applicable_collection_ids' => $this->validCollectionIds(),
            'one_per_customer' => $this->onePerCustomer,
            'customer_eligibility' => 'all',
        ];
    }

    private function normalizedValueAmount(): int
    {
        return match ($this->valueType) {
            'fixed' => Money::fromDecimalString($this->valueAmount),
            'free_shipping' => 0,
            default => (int) round((float) $this->valueAmount),
        };
    }

    /**
     * @return array<int, int>
     */
    private function validProductIds(): array
    {
        return Product::withoutGlobalScopes()
            ->where('store_id', $this->storeId())
            ->whereKey($this->specificProductIds)
            ->pluck('id')
            ->map(fn (int $id): int => $id)
            ->all();
    }

    /**
     * @return array<int, int>
     */
    private function validCollectionIds(): array
    {
        return ProductCollection::withoutGlobalScopes()
            ->where('store_id', $this->storeId())
            ->whereKey($this->specificCollectionIds)
            ->pluck('id')
            ->map(fn (int $id): int => $id)
            ->all();
    }

    private function productBelongsToStore(int $productId): bool
    {
        return Product::withoutGlobalScopes()
            ->where('store_id', $this->storeId())
            ->whereKey($productId)
            ->exists();
    }

    private function collectionBelongsToStore(int $collectionId): bool
    {
        return ProductCollection::withoutGlobalScopes()
            ->where('store_id', $this->storeId())
            ->whereKey($collectionId)
            ->exists();
    }

    private function storeId(): int
    {
        $store = app('current_store');

        abort_unless($store instanceof Store, 404);

        return $store->getKey();
    }

    private function authorizeSave(): void
    {
        if ($this->discount instanceof Discount) {
            $this->authorize('update', $this->discount);

            return;
        }

        $this->authorize('create', Discount::class);
    }

    private function normalizeCode(): void
    {
        if ($this->type !== DiscountType::Code->value) {
            $this->code = '';

            return;
        }

        $this->code = Str::upper(trim($this->code));
    }

    /**
     * @return list<mixed>
     */
    private function valueAmountRules(): array
    {
        return match ($this->valueType) {
            DiscountValueType::Percent->value => ['required', 'integer', 'min:1', 'max:100'],
            DiscountValueType::FreeShipping->value => ['nullable'],
            default => ['required', 'numeric', 'min:0.01'],
        };
    }

    private function statusForPayload(): DiscountStatus
    {
        if ($this->discount?->status === DiscountStatus::Expired) {
            return DiscountStatus::Expired;
        }

        if ($this->isActive) {
            return DiscountStatus::Active;
        }

        if ($this->discount?->status === DiscountStatus::Draft || ! $this->discount instanceof Discount) {
            return DiscountStatus::Draft;
        }

        return DiscountStatus::Disabled;
    }
}


Output:
Chunk ID: 4ed274
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 1817
Output:
<?php

use App\Enums\DiscountType;
use App\Enums\DiscountValueType;
use App\Models\Checkout;
use App\Models\Discount;
use App\Models\InventoryItem;
use App\Models\Product;
use App\Models\ProductVariant;
use App\Models\ShippingRate;
use App\Models\ShippingZone;
use App\Models\Store;
use App\Models\TaxSettings;
use App\Services\CartService;
use App\Services\PricingEngine;
use App\Services\ShippingCalculator;
use App\Services\TaxCalculator;
use Illuminate\Foundation\Testing\RefreshDatabase;

uses(RefreshDatabase::class);

function pricingStore(): Store
{
    $store = Store::factory()->create();
    app()->instance('current_store', $store);

    TaxSettings::withoutGlobalScopes()->create([
        'store_id' => $store->getKey(),
        'mode' => 'manual',
        'provider' => 'none',
        'prices_include_tax' => false,
        'config_json' => [
            'name' => 'VAT',
            'default_rate_bps' => 1900,
            'shipping_taxable' => true,
            'rates' => [
                ['country' => 'DE', 'rate_bps' => 1900, 'name' => 'VAT'],
            ],
        ],
    ]);

    return $store;
}

function pricingVariant(Store $store, int $price = 2500, bool $requiresShipping = true): ProductVariant
{
    $product = Product::factory()
        ->withDefaultVariant($price)
        ->create(['store_id' => $store->getKey()]);
    $variant = ProductVariant::withoutGlobalScopes()
        ->where('product_id', $product->getKey())
        ->firstOrFail();

    $variant->forceFill([
        'requires_shipping' => $requiresShipping,
        'weight_g' => $requiresShipping ? 500 : 0,
    ])->save();
    InventoryItem::withoutGlobalScopes()
        ->where('variant_id', $variant->getKey())
        ->update(['quantity_on_hand' => 20]);

    return $variant->refresh();
}

function pricingCheckout(Store $store, ProductVariant $variant, int $quantity = 2): Checkout
{
    $cart = app(CartService::class)->create($store);
    app(CartService::class)->addLine($cart, $variant->getKey(), $quantity);

    return Checkout::withoutGlobalScopes()->create([
        'store_id' => $store->getKey(),
        'cart_id' => $cart->getKey(),
        'status' => 'shipping_selected',
        'email' => 'buyer@example.test',
        'shipping_address_json' => [
            'first_name' => 'Test',
            'last_name' => 'Buyer',
            'address1' => 'Main Street 1',
            'city' => 'Berlin',
            'country' => 'DE',
            'postal_code' => '10115',
        ],
    ]);
}

test('pricing engine calculates deterministic exclusive totals with shipping tax', function () {
    $store = pricingStore();
    $variant = pricingVariant($store);
    $zone = ShippingZone::withoutGlobalScopes()->create([
        'store_id' => $store->getKey(),
        'name' => 'Germany',
        'countries_json' => ['DE'],
        'regions_json' => [],
    ]);
    $rate = ShippingRate::withoutGlobalScopes()->create([
        'zone_id' => $zone->getKey(),
        'name' => 'Standard',
        'type' => 'flat',
        'config_json' => ['amount' => 499],
        'is_active' => true,
    ]);
    $checkout = pricingCheckout($store, $variant);
    $checkout->forceFill(['shipping_method_id' => $rate->getKey()])->save();

    $result = app(PricingEngine::class)->calculate($checkout);

    expect($result->subtotal)->toBe(5000)
        ->and($result->shipping)->toBe(499)
        ->and($result->taxTotal)->toBe(1045)
        ->and($result->total)->toBe(6544)
        ->and($checkout->refresh()->totals_json['total'])->toBe(6544);
});

test('pricing engine applies percent and free shipping discounts', function () {
    $store = pricingStore();
    $variant = pricingVariant($store);
    $zone = ShippingZone::withoutGlobalScopes()->create([
        'store_id' => $store->getKey(),
        'name' => 'Germany',
        'countries_json' => ['DE'],
        'regions_json' => [],
    ]);
    $rate = ShippingRate::withoutGlobalScopes()->create([
        'zone_id' => $zone->getKey(),
        'name' => 'Standard',
        'type' => 'flat',
        'config_json' => ['amount' => 499],
        'is_active' => true,
    ]);
    Discount::factory()->create(['store_id' => $store->getKey(), 'code' => 'SAVE10']);
    Discount::factory()->freeShipping()->create(['store_id' => $store->getKey(), 'code' => 'FREESHIP']);
    $checkout = pricingCheckout($store, $variant);
    $checkout->forceFill([
        'shipping_method_id' => $rate->getKey(),
        'discount_code' => 'save10',
    ])->save();

    $discounted = app(PricingEngine::class)->calculate($checkout);

    expect($discounted->discount)->toBe(500)
        ->and($discounted->shipping)->toBe(499)
        ->and($discounted->total)->toBe(5949);

    $checkout->forceFill(['discount_code' => 'FREESHIP'])->save();
    $freeShipping = app(PricingEngine::class)->calculate($checkout);

    expect($freeShipping->discount)->toBe(0)
        ->and($freeShipping->shipping)->toBe(0)
        ->and($freeShipping->total)->toBe(5950);
});

test('pricing engine applies active automatic discounts', function () {
    $store = pricingStore();
    $variant = pricingVariant($store);
    $checkout = pricingCheckout($store, $variant);
    Discount::factory()->create([
        'store_id' => $store->getKey(),
        'type' => DiscountType::Automatic,
        'code' => null,
        'value_type' => DiscountValueType::Percent,
        'value_amount' => 10,
    ]);

    $result = app(PricingEngine::class)->calculate($checkout);
    $line = $checkout->cart->lines()->firstOrFail();

    expect($result->discount)->toBe(500)
        ->and($result->total)->toBe(5355)
        ->and($line->refresh()->line_discount_amount)->toBe(500)
        ->and($line->line_total_amount)->toBe(4500);
});

test('shipping and tax calculators handle matching ranges and inclusive extraction', function () {
    $store = pricingStore();
    $physicalVariant = pricingVariant($store, requiresShipping: true);
    $digitalVariant = pricingVariant($store, requiresShipping: false);
    $cart = app(CartService::class)->create($store);
    app(CartService::class)->addLine($cart, $physicalVariant->getKey(), 2);
    app(CartService::class)->addLine($cart, $digitalVariant->getKey(), 1);
    $zone = ShippingZone::withoutGlobalScopes()->create([
        'store_id' => $store->getKey(),
        'name' => 'Berlin',
        'countries_json' => ['DE'],
        'regions_json' => ['DE-BE'],
    ]);
    $rate = ShippingRate::withoutGlobalScopes()->create([
        'zone_id' => $zone->getKey(),
        'name' => 'Weight',
        'type' => 'weight',
        'config_json' => [
            'ranges' => [
                ['min_g' => 0, 'max_g' => 500, 'amount' => 499],
                ['min_g' => 501, 'max_g' => 2000, 'amount' => 899],
            ],
        ],
        'is_active' => true,
    ]);

    $rates = app(ShippingCalculator::class)->getAvailableRates($store, ['country' => 'DE', 'province_code' => 'DE-BE']);

    expect($rates->first()?->getKey())->toBe($rate->getKey())
        ->and(app(ShippingCalculator::class)->calculate($rate, $cart))->toBe(899)
        ->and(app(TaxCalculator::class)->extractInclusive(11900, 1900))->toBe(1900)
        ->and(app(TaxCalculator::class)->addExclusive(10000, 1900))->toBe(1900);
});


sed -n '1,280p' tests/Feature/Admin/DiscountManagementTest.php


sed -n '1,220p' app/Livewire/Admin/Discounts/Index.php


sed -n '1,220p' app/Enums/DiscountStatus.php app/Models/Discount.php database/factories/DiscountFactory.php


sed -n '1,280p' tests/Feature/Admin/DiscountManagementTest.php

<?php

use App\Enums\DiscountStatus;
use App\Enums\DiscountType;
use App\Enums\DiscountValueType;
use App\Enums\StoreUserRole;
use App\Http\Middleware\CheckStoreRole;
use App\Http\Middleware\EnsureUserEmailIsVerified;
use App\Http\Middleware\ResolveStore;
use App\Livewire\Admin\Discounts\Form as AdminDiscountForm;
use App\Livewire\Admin\Discounts\Index as AdminDiscountsIndex;
use App\Models\Collection;
use App\Models\Discount;
use App\Models\Product;
use App\Models\Store;
use App\Models\User;
use Database\Seeders\DatabaseSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;

uses(RefreshDatabase::class);

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

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

    return $store;
}

function adminDiscountManagementUser(): User
{
    return User::query()->where('email', 'admin@acme.test')->firstOrFail();
}

function adminDiscountManagementSupportUser(Store $store): User
{
    $user = User::factory()->create();
    $user->stores()->attach($store->getKey(), [
        'role' => StoreUserRole::Support->value,
        'created_at' => now(),
    ]);

    return $user;
}

test('livewire persists store middleware for admin action requests', function (): void {
    expect(Livewire::getPersistentMiddleware())
        ->toContain(EnsureUserEmailIsVerified::class)
        ->toContain(ResolveStore::class)
        ->toContain(CheckStoreRole::class);
});

test('admin discount routes require authentication and render store scoped discounts', function (): void {
    $store = adminDiscountManagementStore();
    $discount = Discount::factory()->create([
        'store_id' => $store->getKey(),
        'code' => 'SAVE20',
        'value_type' => DiscountValueType::Percent,
        'value_amount' => 20,
        'usage_count' => 3,
        'usage_limit' => 100,
    ]);
    Discount::factory()->create([
        'store_id' => Store::factory()->create()->getKey(),
        'code' => 'OTHER20',
    ]);

    $this->get('/admin/discounts')->assertRedirect('/admin/login');

    $this->actingAs(adminDiscountManagementUser())
        ->withSession(['current_store_id' => $store->getKey()])
        ->get('/admin/discounts')
        ->assertSuccessful()
        ->assertSee('SAVE20')
        ->assertSee('20%')
        ->assertSee('3 / 100')
        ->assertDontSee('OTHER20');

    $this->actingAs(adminDiscountManagementUser())
        ->withSession(['current_store_id' => $store->getKey()])
        ->get('/admin/discounts/create')
        ->assertSuccessful()
        ->assertSee('Create discount');

    $this->actingAs(adminDiscountManagementUser())
        ->withSession(['current_store_id' => $store->getKey()])
        ->get('/admin/discounts/'.$discount->getKey().'/edit')
        ->assertSuccessful()
        ->assertSee('SAVE20');
});

test('admin discount index filters by code and effective status', function (): void {
    $store = adminDiscountManagementStore();
    $user = adminDiscountManagementUser();
    Discount::factory()->create([
        'store_id' => $store->getKey(),
        'code' => 'ACTIVE10',
    ]);
    Discount::factory()->create([
        'store_id' => $store->getKey(),
        'code' => 'SOON10',
        'starts_at' => now()->addWeek(),
    ]);

    Livewire::actingAs($user)
        ->test(AdminDiscountsIndex::class)
        ->assertSee('ACTIVE10')
        ->assertSee('SOON10')
        ->set('search', 'active')
        ->assertSee('ACTIVE10')
        ->assertDontSee('SOON10')
        ->set('search', '')
        ->set('statusFilter', 'scheduled')
        ->assertSee('SOON10')
        ->assertDontSee('ACTIVE10')
        ->set('statusFilter', 'all')
        ->set('typeFilter', 'automatic')
        ->assertDontSee('ACTIVE10')
        ->assertDontSee('SOON10');
});

test('admin discount form creates discounts with eligibility rules', function (): void {
    $store = adminDiscountManagementStore();
    $user = adminDiscountManagementUser();
    $product = Product::withoutGlobalScopes()->where('store_id', $store->getKey())->firstOrFail();
    $collection = Collection::withoutGlobalScopes()->where('store_id', $store->getKey())->firstOrFail();

    Livewire::actingAs($user)
        ->test(AdminDiscountForm::class)
        ->set('type', 'code')
        ->set('code', 'VIP25')
        ->set('valueType', 'fixed')
        ->set('valueAmount', '5.00')
        ->set('minimumPurchaseAmount', '25.00')
        ->set('usageLimit', '100')
        ->set('onePerCustomer', true)
        ->call('addProduct', $product->getKey())
        ->call('addCollection', $collection->getKey())
        ->call('save')
        ->assertHasNoErrors();

    $discount = Discount::withoutGlobalScopes()
        ->where('store_id', $store->getKey())
        ->where('code', 'VIP25')
        ->firstOrFail();

    expect($discount->value_type)->toBe(DiscountValueType::Fixed)
        ->and($discount->value_amount)->toBe(500)
        ->and($discount->usage_limit)->toBe(100)
        ->and(data_get($discount->rules_json, 'min_purchase_amount'))->toBe(2500)
        ->and(data_get($discount->rules_json, 'one_per_customer'))->toBeTrue()
        ->and(data_get($discount->rules_json, 'applicable_product_ids'))->toBe([$product->getKey()])
        ->and(data_get($discount->rules_json, 'applicable_collection_ids'))->toBe([$collection->getKey()]);
});

test('admin discount form enforces mutation policies and verified users', function (): void {
    $store = adminDiscountManagementStore();
    $supportUser = adminDiscountManagementSupportUser($store);
    $unverifiedUser = User::factory()->unverified()->create();
    $unverifiedUser->stores()->attach($store->getKey(), [
        'role' => StoreUserRole::Admin->value,
        'created_at' => now(),
    ]);

    $this->actingAs($supportUser)
        ->withSession(['current_store_id' => $store->getKey()])
        ->get('/admin/discounts')
        ->assertSuccessful();

    $this->actingAs($supportUser)
        ->withSession(['current_store_id' => $store->getKey()])
        ->get('/admin/discounts/create')
        ->assertForbidden();

    $this->actingAs($unverifiedUser)
        ->withSession(['current_store_id' => $store->getKey()])
        ->get('/admin/discounts/create')
        ->assertRedirect('/email/verify');

    Livewire::actingAs($supportUser)
        ->test(AdminDiscountForm::class)
        ->assertStatus(403);
});

test('admin discount form validates percentage values and normalized code uniqueness', function (): void {
    $store = adminDiscountManagementStore();
    $user = adminDiscountManagementUser();
    Discount::factory()->create([
        'store_id' => $store->getKey(),
        'code' => 'SAVE20',
    ]);

    Livewire::actingAs($user)
        ->test(AdminDiscountForm::class)
        ->set('code', ' save20 ')
        ->set('valueType', 'percent')
        ->set('valueAmount', '101')
        ->call('save')
        ->assertHasErrors(['code', 'valueAmount']);

    Livewire::actingAs($user)
        ->test(AdminDiscountForm::class)
        ->set('code', 'UNIQUE20')
        ->set('valueType', 'percent')
        ->set('valueAmount', '10.5')
        ->call('save')
        ->assertHasErrors(['valueAmount']);
});

test('admin discount form creates drafts by default and preserves expired discounts', function (): void {
    $store = adminDiscountManagementStore();
    $user = adminDiscountManagementUser();

    Livewire::actingAs($user)
        ->test(AdminDiscountForm::class)
        ->set('code', 'DRAFT10')
        ->call('save')
        ->assertHasNoErrors();

    $draft = Discount::withoutGlobalScopes()
        ->where('store_id', $store->getKey())
        ->where('code', 'DRAFT10')
        ->firstOrFail();

    $expired = Discount::factory()->create([
        'store_id' => $store->getKey(),
        'code' => 'EXPIRED10',
        'status' => DiscountStatus::Expired,
        'starts_at' => now()->subMonth(),
        'ends_at' => now()->subDay(),
    ]);

    Livewire::actingAs($user)
        ->test(AdminDiscountForm::class, ['discount' => $expired])
        ->set('isActive', true)
        ->set('endsAt', now()->addMonth()->format('Y-m-d\TH:i'))
        ->call('save')
        ->assertHasNoErrors();

    expect($draft->status)->toBe(DiscountStatus::Draft)
        ->and($expired->refresh()->status)->toBe(DiscountStatus::Expired);
});

test('admin discount form edits discounts and rejects another store', function (): void {
    $store = adminDiscountManagementStore();
    $user = adminDiscountManagementUser();
    $discount = Discount::factory()->create([
        'store_id' => $store->getKey(),
        'code' => 'EDITME',
    ]);
    $otherDiscount = Discount::factory()->create([
        'store_id' => Store::factory()->create()->getKey(),
        'code' => 'OTHEREDIT',
    ]);

    Livewire::actingAs($user)
        ->test(AdminDiscountForm::class, ['discount' => $discount])
        ->set('type', 'automatic')
        ->set('valueType', 'free_shipping')
        ->set('isActive', false)
        ->call('save')
        ->assertHasNoErrors();

    expect($discount->refresh()->type)->toBe(DiscountType::Automatic)
        ->and($discount->code)->toBeNull()
        ->and($discount->value_type)->toBe(DiscountValueType::FreeShipping)
        ->and($discount->status)->toBe(DiscountStatus::Disabled);

    Livewire::actingAs($user)
        ->test(AdminDiscountForm::class, ['discount' => $otherDiscount])
        ->assertStatus(404);
});


Output:
Chunk ID: 3f7c1a
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 2406
Output:
<?php

use App\Enums\DiscountStatus;
use App\Enums\DiscountType;
use App\Enums\DiscountValueType;
use App\Enums\StoreUserRole;
use App\Http\Middleware\CheckStoreRole;
use App\Http\Middleware\EnsureUserEmailIsVerified;
use App\Http\Middleware\ResolveStore;
use App\Livewire\Admin\Discounts\Form as AdminDiscountForm;
use App\Livewire\Admin\Discounts\Index as AdminDiscountsIndex;
use App\Models\Collection;
use App\Models\Discount;
use App\Models\Product;
use App\Models\Store;
use App\Models\User;
use Database\Seeders\DatabaseSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;

uses(RefreshDatabase::class);

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

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

    return $store;
}

function adminDiscountManagementUser(): User
{
    return User::query()->where('email', 'admin@acme.test')->firstOrFail();
}

function adminDiscountManagementSupportUser(Store $store): User
{
    $user = User::factory()->create();
    $user->stores()->attach($store->getKey(), [
        'role' => StoreUserRole::Support->value,
        'created_at' => now(),
    ]);

    return $user;
}

test('livewire persists store middleware for admin action requests', function (): void {
    expect(Livewire::getPersistentMiddleware())
        ->toContain(EnsureUserEmailIsVerified::class)
        ->toContain(ResolveStore::class)
        ->toContain(CheckStoreRole::class);
});

test('admin discount routes require authentication and render store scoped discounts', function (): void {
    $store = adminDiscountManagementStore();
    $discount = Discount::factory()->create([
        'store_id' => $store->getKey(),
        'code' => 'SAVE20',
        'value_type' => DiscountValueType::Percent,
        'value_amount' => 20,
        'usage_count' => 3,
        'usage_limit' => 100,
    ]);
    Discount::factory()->create([
        'store_id' => Store::factory()->create()->getKey(),
        'code' => 'OTHER20',
    ]);

    $this->get('/admin/discounts')->assertRedirect('/admin/login');

    $this->actingAs(adminDiscountManagementUser())
        ->withSession(['current_store_id' => $store->getKey()])
        ->get('/admin/discounts')
        ->assertSuccessful()
        ->assertSee('SAVE20')
        ->assertSee('20%')
        ->assertSee('3 / 100')
        ->assertDontSee('OTHER20');

    $this->actingAs(adminDiscountManagementUser())
        ->withSession(['current_store_id' => $store->getKey()])
        ->get('/admin/discounts/create')
        ->assertSuccessful()
        ->assertSee('Create discount');

    $this->actingAs(adminDiscountManagementUser())
        ->withSession(['current_store_id' => $store->getKey()])
        ->get('/admin/discounts/'.$discount->getKey().'/edit')
        ->assertSuccessful()
        ->assertSee('SAVE20');
});

test('admin discount index filters by code and effective status', function (): void {
    $store = adminDiscountManagementStore();
    $user = adminDiscountManagementUser();
    Discount::factory()->create([
        'store_id' => $store->getKey(),
        'code' => 'ACTIVE10',
    ]);
    Discount::factory()->create([
        'store_id' => $store->getKey(),
        'code' => 'SOON10',
        'starts_at' => now()->addWeek(),
    ]);

    Livewire::actingAs($user)
        ->test(AdminDiscountsIndex::class)
        ->assertSee('ACTIVE10')
        ->assertSee('SOON10')
        ->set('search', 'active')
        ->assertSee('ACTIVE10')
        ->assertDontSee('SOON10')
        ->set('search', '')
        ->set('statusFilter', 'scheduled')
        ->assertSee('SOON10')
        ->assertDontSee('ACTIVE10')
        ->set('statusFilter', 'all')
        ->set('typeFilter', 'automatic')
        ->assertDontSee('ACTIVE10')
        ->assertDontSee('SOON10');
});

test('admin discount form creates discounts with eligibility rules', function (): void {
    $store = adminDiscountManagementStore();
    $user = adminDiscountManagementUser();
    $product = Product::withoutGlobalScopes()->where('store_id', $store->getKey())->firstOrFail();
    $collection = Collection::withoutGlobalScopes()->where('store_id', $store->getKey())->firstOrFail();

    Livewire::actingAs($user)
        ->test(AdminDiscountForm::class)
        ->set('type', 'code')
        ->set('code', 'VIP25')
        ->set('valueType', 'fixed')
        ->set('valueAmount', '5.00')
        ->set('minimumPurchaseAmount', '25.00')
        ->set('usageLimit', '100')
        ->set('onePerCustomer', true)
        ->call('addProduct', $product->getKey())
        ->call('addCollection', $collection->getKey())
        ->call('save')
        ->assertHasNoErrors();

    $discount = Discount::withoutGlobalScopes()
        ->where('store_id', $store->getKey())
        ->where('code', 'VIP25')
        ->firstOrFail();

    expect($discount->value_type)->toBe(DiscountValueType::Fixed)
        ->and($discount->value_amount)->toBe(500)
        ->and($discount->usage_limit)->toBe(100)
        ->and(data_get($discount->rules_json, 'min_purchase_amount'))->toBe(2500)
        ->and(data_get($discount->rules_json, 'one_per_customer'))->toBeTrue()
        ->and(data_get($discount->rules_json, 'applicable_product_ids'))->toBe([$product->getKey()])
        ->and(data_get($discount->rules_json, 'applicable_collection_ids'))->toBe([$collection->getKey()]);
});

test('admin discount form enforces mutation policies and verified users', function (): void {
    $store = adminDiscountManagementStore();
    $supportUser = adminDiscountManagementSupportUser($store);
    $unverifiedUser = User::factory()->unverified()->create();
    $unverifiedUser->stores()->attach($store->getKey(), [
        'role' => StoreUserRole::Admin->value,
        'created_at' => now(),
    ]);

    $this->actingAs($supportUser)
        ->withSession(['current_store_id' => $store->getKey()])
        ->get('/admin/discounts')
        ->assertSuccessful();

    $this->actingAs($supportUser)
        ->withSession(['current_store_id' => $store->getKey()])
        ->get('/admin/discounts/create')
        ->assertForbidden();

    $this->actingAs($unverifiedUser)
        ->withSession(['current_store_id' => $store->getKey()])
        ->get('/admin/discounts/create')
        ->assertRedirect('/email/verify');

    Livewire::actingAs($supportUser)
        ->test(AdminDiscountForm::class)
        ->assertStatus(403);
});

test('admin discount form validates percentage values and normalized code uniqueness', function (): void {
    $store = adminDiscountManagementStore();
    $user = adminDiscountManagementUser();
    Discount::factory()->create([
        'store_id' => $store->getKey(),
        'code' => 'SAVE20',
    ]);

    Livewire::actingAs($user)
        ->test(AdminDiscountForm::class)
        ->set('code', ' save20 ')
        ->set('valueType', 'percent')
        ->set('valueAmount', '101')
        ->call('save')
        ->assertHasErrors(['code', 'valueAmount']);

    Livewire::actingAs($user)
        ->test(AdminDiscountForm::class)
        ->set('code', 'UNIQUE20')
        ->set('valueType', 'percent')
        ->set('valueAmount', '10.5')
        ->call('save')
        ->assertHasErrors(['valueAmount']);
});

test('admin discount form creates drafts by default and preserves expired discounts', function (): void {
    $store = adminDiscountManagementStore();
    $user = adminDiscountManagementUser();

    Livewire::actingAs($user)
        ->test(AdminDiscountForm::class)
        ->set('code', 'DRAFT10')
        ->call('save')
        ->assertHasNoErrors();

    $draft = Discount::withoutGlobalScopes()
        ->where('store_id', $store->getKey())
        ->where('code', 'DRAFT10')
        ->firstOrFail();

    $expired = Discount::factory()->create([
        'store_id' => $store->getKey(),
        'code' => 'EXPIRED10',
        'status' => DiscountStatus::Expired,
        'starts_at' => now()->subMonth(),
        'ends_at' => now()->subDay(),
    ]);

    Livewire::actingAs($user)
        ->test(AdminDiscountForm::class, ['discount' => $expired])
        ->set('isActive', true)
        ->set('endsAt', now()->addMonth()->format('Y-m-d\TH:i'))
        ->call('save')
        ->assertHasNoErrors();

    expect($draft->status)->toBe(DiscountStatus::Draft)
        ->and($expired->refresh()->status)->toBe(DiscountStatus::Expired);
});

test('admin discount form edits discounts and rejects another store', function (): void {
    $store = adminDiscountManagementStore();
    $user = adminDiscountManagementUser();
    $discount = Discount::factory()->create([
        'store_id' => $store->getKey(),
        'code' => 'EDITME',
    ]);
    $otherDiscount = Discount::factory()->create([
        'store_id' => Store::factory()->create()->getKey(),
        'code' => 'OTHEREDIT',
    ]);

    Livewire::actingAs($user)
        ->test(AdminDiscountForm::class, ['discount' => $discount])
        ->set('type', 'automatic')
        ->set('valueType', 'free_shipping')
        ->set('isActive', false)
        ->call('save')
        ->assertHasNoErrors();

    expect($discount->refresh()->type)->toBe(DiscountType::Automatic)
        ->and($discount->code)->toBeNull()
        ->and($discount->value_type)->toBe(DiscountValueType::FreeShipping)
        ->and($discount->status)->toBe(DiscountStatus::Disabled);

    Livewire::actingAs($user)
        ->test(AdminDiscountForm::class, ['discount' => $otherDiscount])
        ->assertStatus(404);
});


sed -n '1,220p' app/Livewire/Admin/Discounts/Index.php

<?php

namespace App\Livewire\Admin\Discounts;

use App\Enums\DiscountStatus;
use App\Enums\DiscountValueType;
use App\Models\Discount;
use App\Models\Store;
use App\Support\Money;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Livewire\Attributes\Locked;
use Livewire\Component;
use Livewire\WithPagination;

class Index extends Component
{
    use AuthorizesRequests;
    use WithPagination;

    #[Locked]
    public int $storeId;

    public string $storeCurrency = 'EUR';

    public string $search = '';

    public string $statusFilter = 'all';

    public string $typeFilter = 'all';

    public function mount(): void
    {
        $store = app('current_store');

        abort_unless($store instanceof Store, 404);

        $this->authorize('viewAny', Discount::class);

        $this->storeId = $store->getKey();
        $this->storeCurrency = $store->default_currency;
    }

    public function updatedSearch(): void
    {
        $this->resetPage();
    }

    public function updatedStatusFilter(): void
    {
        $this->resetPage();
    }

    public function updatedTypeFilter(): void
    {
        $this->resetPage();
    }

    public function discounts(): LengthAwarePaginator
    {
        return Discount::withoutGlobalScopes()
            ->where('store_id', $this->storeId)
            ->when($this->search !== '', function (Builder $query): void {
                $search = '%'.$this->search.'%';

                $query->where(function (Builder $query) use ($search): void {
                    $query
                        ->where('code', 'like', $search)
                        ->orWhere('type', 'like', $search);
                });
            })
            ->when($this->statusFilter !== 'all', fn (Builder $query) => $this->applyStatusFilter($query))
            ->when($this->typeFilter !== 'all', fn (Builder $query) => $query->where('type', $this->typeFilter))
            ->latest('starts_at')
            ->latest('id')
            ->paginate(20);
    }

    public function valueLabel(Discount $discount): string
    {
        return match ($discount->value_type) {
            DiscountValueType::Percent => $discount->value_amount.'%',
            DiscountValueType::Fixed => Money::format($discount->value_amount, $this->storeCurrency),
            DiscountValueType::FreeShipping => 'Free shipping',
        };
    }

    public function effectiveStatus(Discount $discount): string
    {
        if ($discount->status === DiscountStatus::Disabled) {
            return 'disabled';
        }

        if ($discount->starts_at->isFuture()) {
            return 'scheduled';
        }

        if ($discount->status === DiscountStatus::Expired || ($discount->ends_at !== null && $discount->ends_at->isPast())) {
            return 'expired';
        }

        return $discount->status->value;
    }

    public function statusColor(string $status): string
    {
        return match ($status) {
            'active' => 'green',
            'expired' => 'red',
            'scheduled' => 'amber',
            default => 'zinc',
        };
    }

    public function render(): mixed
    {
        return view('livewire.admin.discounts.index', [
            'discounts' => $this->discounts(),
        ])->layout('layouts.app', [
            'title' => __('Discounts'),
        ]);
    }

    private function applyStatusFilter(Builder $query): void
    {
        match ($this->statusFilter) {
            'active' => $query
                ->where('status', DiscountStatus::Active->value)
                ->where('starts_at', '<=', now())
                ->where(function (Builder $query): void {
                    $query->whereNull('ends_at')->orWhere('ends_at', '>=', now());
                }),
            'expired' => $query->where(function (Builder $query): void {
                $query->where('status', DiscountStatus::Expired->value)->orWhere('ends_at', '<', now());
            }),
            'scheduled' => $query->where('starts_at', '>', now()),
            default => null,
        };
    }
}


Output:
Chunk ID: 10bb98
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 1042
Output:
<?php

namespace App\Livewire\Admin\Discounts;

use App\Enums\DiscountStatus;
use App\Enums\DiscountValueType;
use App\Models\Discount;
use App\Models\Store;
use App\Support\Money;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Livewire\Attributes\Locked;
use Livewire\Component;
use Livewire\WithPagination;

class Index extends Component
{
    use AuthorizesRequests;
    use WithPagination;

    #[Locked]
    public int $storeId;

    public string $storeCurrency = 'EUR';

    public string $search = '';

    public string $statusFilter = 'all';

    public string $typeFilter = 'all';

    public function mount(): void
    {
        $store = app('current_store');

        abort_unless($store instanceof Store, 404);

        $this->authorize('viewAny', Discount::class);

        $this->storeId = $store->getKey();
        $this->storeCurrency = $store->default_currency;
    }

    public function updatedSearch(): void
    {
        $this->resetPage();
    }

    public function updatedStatusFilter(): void
    {
        $this->resetPage();
    }

    public function updatedTypeFilter(): void
    {
        $this->resetPage();
    }

    public function discounts(): LengthAwarePaginator
    {
        return Discount::withoutGlobalScopes()
            ->where('store_id', $this->storeId)
            ->when($this->search !== '', function (Builder $query): void {
                $search = '%'.$this->search.'%';

                $query->where(function (Builder $query) use ($search): void {
                    $query
                        ->where('code', 'like', $search)
                        ->orWhere('type', 'like', $search);
                });
            })
            ->when($this->statusFilter !== 'all', fn (Builder $query) => $this->applyStatusFilter($query))
            ->when($this->typeFilter !== 'all', fn (Builder $query) => $query->where('type', $this->typeFilter))
            ->latest('starts_at')
            ->latest('id')
            ->paginate(20);
    }

    public function valueLabel(Discount $discount): string
    {
        return match ($discount->value_type) {
            DiscountValueType::Percent => $discount->value_amount.'%',
            DiscountValueType::Fixed => Money::format($discount->value_amount, $this->storeCurrency),
            DiscountValueType::FreeShipping => 'Free shipping',
        };
    }

    public function effectiveStatus(Discount $discount): string
    {
        if ($discount->status === DiscountStatus::Disabled) {
            return 'disabled';
        }

        if ($discount->starts_at->isFuture()) {
            return 'scheduled';
        }

        if ($discount->status === DiscountStatus::Expired || ($discount->ends_at !== null && $discount->ends_at->isPast())) {
            return 'expired';
        }

        return $discount->status->value;
    }

    public function statusColor(string $status): string
    {
        return match ($status) {
            'active' => 'green',
            'expired' => 'red',
            'scheduled' => 'amber',
            default => 'zinc',
        };
    }

    public function render(): mixed
    {
        return view('livewire.admin.discounts.index', [
            'discounts' => $this->discounts(),
        ])->layout('layouts.app', [
            'title' => __('Discounts'),
        ]);
    }

    private function applyStatusFilter(Builder $query): void
    {
        match ($this->statusFilter) {
            'active' => $query
                ->where('status', DiscountStatus::Active->value)
                ->where('starts_at', '<=', now())
                ->where(function (Builder $query): void {
                    $query->whereNull('ends_at')->orWhere('ends_at', '>=', now());
                }),
            'expired' => $query->where(function (Builder $query): void {
                $query->where('status', DiscountStatus::Expired->value)->orWhere('ends_at', '<', now());
            }),
            'scheduled' => $query->where('starts_at', '>', now()),
            default => null,
        };
    }
}


sed -n '1,220p' app/Enums/DiscountStatus.php app/Models/Discount.php database/factories/DiscountFactory.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,
        ];
    }
}
<?php

namespace Database\Factories;

use App\Enums\DiscountStatus;
use App\Enums\DiscountType;
use App\Enums\DiscountValueType;
use App\Models\Store;
use Illuminate\Database\Eloquent\Factories\Factory;

/**
 * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Discount>
 */
class DiscountFactory extends Factory
{
    /**
     * Define the model's default state.
     *
     * @return array<string, mixed>
     */
    public function definition(): array
    {
        return [
            'store_id' => Store::factory(),
            'type' => DiscountType::Code,
            'code' => fake()->unique()->bothify('SAVE##'),
            'value_type' => DiscountValueType::Percent,
            'value_amount' => 10,
            'starts_at' => now()->subDay(),
            'ends_at' => now()->addMonth(),
            'usage_limit' => null,
            'usage_count' => 0,
            'rules_json' => ['customer_eligibility' => 'all'],
            'status' => DiscountStatus::Active,
        ];
    }

    public function fixed(int $amount = 500): static
    {
        return $this->state(fn (array $attributes): array => [
            'value_type' => DiscountValueType::Fixed,
            'value_amount' => $amount,
        ]);
    }

    public function freeShipping(): static
    {
        return $this->state(fn (array $attributes): array => [
            'value_type' => DiscountValueType::FreeShipping,
            'value_amount' => 0,
        ]);
    }
}


Output:
Chunk ID: 844498
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 823
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,
        ];
    }
}
<?php

namespace Database\Factories;

use App\Enums\DiscountStatus;
use App\Enums\DiscountType;
use App\Enums\DiscountValueType;
use App\Models\Store;
use Illuminate\Database\Eloquent\Factories\Factory;

/**
 * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Discount>
 */
class DiscountFactory extends Factory
{
    /**
     * Define the model's default state.
     *
     * @return array<string, mixed>
     */
    public function definition(): array
    {
        return [
            'store_id' => Store::factory(),
            'type' => DiscountType::Code,
            'code' => fake()->unique()->bothify('SAVE##'),
            'value_type' => DiscountValueType::Percent,
            'value_amount' => 10,
            'starts_at' => now()->subDay(),
            'ends_at' => now()->addMonth(),
            'usage_limit' => null,
            'usage_count' => 0,
            'rules_json' => ['customer_eligibility' => 'all'],
            'status' => DiscountStatus::Active,
        ];
    }

    public function fixed(int $amount = 500): static
    {
        return $this->state(fn (array $attributes): array => [
            'value_type' => DiscountValueType::Fixed,
            'value_amount' => $amount,
        ]);
    }

    public function freeShipping(): static
    {
        return $this->state(fn (array $attributes): array => [
            'value_type' => DiscountValueType::FreeShipping,
            'value_amount' => 0,
        ]);
    }
}


The review found two narrow behavior issues that tests did not pin down: draft/expired discounts were shown as active in the edit form, and the status filter did not exactly match the effective-status logic for disabled rows. I’m patching those and adding focused assertions, plus a combined explicit+automatic pricing test.


Input:
*** Begin Patch
*** Update File: /Users/fabianwesner/Herd/shop/app/Livewire/Admin/Discounts/Form.php
@@
-        $this->isActive = $discount->status !== DiscountStatus::Disabled;
+        $this->isActive = $discount->status === DiscountStatus::Active;
*** End Patch


Success. Updated the following files:
M /Users/fabianwesner/Herd/shop/app/Livewire/Admin/Discounts/Form.php

@@ -271,3 +271,3 @@
         $this->endsAt = $discount->ends_at?->format('Y-m-d\TH:i') ?? '';
-        $this->isActive = $discount->status !== DiscountStatus::Disabled;
+        $this->isActive = $discount->status === DiscountStatus::Active;
     }


Output: {"output":"Success. Updated the following files:\nM /Users/fabianwesner/Herd/shop/app/Livewire/Admin/Discounts/Form.php\n","metadata":{"exit_code":0,"duration_seconds":0.0}}


Input:
*** Begin Patch
*** Update File: /Users/fabianwesner/Herd/shop/app/Livewire/Admin/Discounts/Index.php
@@
             }),
             'expired' => $query->where(function (Builder $query): void {
-                $query->where('status', DiscountStatus::Expired->value)->orWhere('ends_at', '<', now());
+                $query
+                    ->where('status', DiscountStatus::Expired->value)
+                    ->orWhere(function (Builder $query): void {
+                        $query
+                            ->where('status', DiscountStatus::Active->value)
+                            ->where('ends_at', '<', now());
+                    });
             }),
-            'scheduled' => $query->where('starts_at', '>', now()),
+            'scheduled' => $query
+                ->where('status', DiscountStatus::Active->value)
+                ->where('starts_at', '>', now()),
             default => null,
         };
     }
 }
*** End Patch


Success. Updated the following files:
M /Users/fabianwesner/Herd/shop/app/Livewire/Admin/Discounts/Index.php

@@ -132,7 +132,15 @@
                     $query->whereNull('ends_at')->orWhere('ends_at', '>=', now());
-                }),
+            }),
             'expired' => $query->where(function (Builder $query): void {
-                $query->where('status', DiscountStatus::Expired->value)->orWhere('ends_at', '<', now());
+                $query
+                    ->where('status', DiscountStatus::Expired->value)
+                    ->orWhere(function (Builder $query): void {
+                        $query
+                            ->where('status', DiscountStatus::Active->value)
+                            ->where('ends_at', '<', now());
+                    });
             }),
-            'scheduled' => $query->where('starts_at', '>', now()),
+            'scheduled' => $query
+                ->where('status', DiscountStatus::Active->value)
+                ->where('starts_at', '>', now()),
             default => null,


Output: {"output":"Success. Updated the following files:\nM /Users/fabianwesner/Herd/shop/app/Livewire/Admin/Discounts/Index.php\n","metadata":{"exit_code":0,"duration_seconds":0.0}}


Input:
*** Begin Patch
*** Update File: /Users/fabianwesner/Herd/shop/tests/Feature/Admin/DiscountManagementTest.php
@@
     Discount::factory()->create([
         'store_id' => $store->getKey(),
         'code' => 'SOON10',
         'starts_at' => now()->addWeek(),
     ]);
+    Discount::factory()->create([
+        'store_id' => $store->getKey(),
+        'code' => 'DISABLEDSOON',
+        'status' => DiscountStatus::Disabled,
+        'starts_at' => now()->addWeek(),
+    ]);
+    Discount::factory()->create([
+        'store_id' => $store->getKey(),
+        'code' => 'ENDED10',
+        'starts_at' => now()->subMonth(),
+        'ends_at' => now()->subDay(),
+    ]);
+    Discount::factory()->create([
+        'store_id' => $store->getKey(),
+        'code' => 'DISABLEDENDED',
+        'status' => DiscountStatus::Disabled,
+        'starts_at' => now()->subMonth(),
+        'ends_at' => now()->subDay(),
+    ]);

     Livewire::actingAs($user)
         ->test(AdminDiscountsIndex::class)
         ->assertSee('ACTIVE10')
         ->assertSee('SOON10')
@@
         ->set('search', '')
         ->set('statusFilter', 'scheduled')
         ->assertSee('SOON10')
         ->assertDontSee('ACTIVE10')
+        ->assertDontSee('DISABLEDSOON')
+        ->set('statusFilter', 'expired')
+        ->assertSee('ENDED10')
+        ->assertDontSee('DISABLEDENDED')
         ->set('statusFilter', 'all')
         ->set('typeFilter', 'automatic')
         ->assertDontSee('ACTIVE10')
         ->assertDontSee('SOON10');
@@
     $draft = Discount::withoutGlobalScopes()
         ->where('store_id', $store->getKey())
         ->where('code', 'DRAFT10')
         ->firstOrFail();

+    Livewire::actingAs($user)
+        ->test(AdminDiscountForm::class, ['discount' => $draft])
+        ->assertSet('isActive', false);
+
     $expired = Discount::factory()->create([
         'store_id' => $store->getKey(),
         'code' => 'EXPIRED10',
         'status' => DiscountStatus::Expired,
         'starts_at' => now()->subMonth(),
         'ends_at' => now()->subDay(),
     ]);

     Livewire::actingAs($user)
         ->test(AdminDiscountForm::class, ['discount' => $expired])
+        ->assertSet('isActive', false)
         ->set('isActive', true)
         ->set('endsAt', now()->addMonth()->format('Y-m-d\TH:i'))
         ->call('save')
         ->assertHasNoErrors();
*** End Patch


Success. Updated the following files:
M /Users/fabianwesner/Herd/shop/tests/Feature/Admin/DiscountManagementTest.php

@@ -109,2 +109,21 @@
     ]);
+    Discount::factory()->create([
+        'store_id' => $store->getKey(),
+        'code' => 'DISABLEDSOON',
+        'status' => DiscountStatus::Disabled,
+        'starts_at' => now()->addWeek(),
+    ]);
+    Discount::factory()->create([
+        'store_id' => $store->getKey(),
+        'code' => 'ENDED10',
+        'starts_at' => now()->subMonth(),
+        'ends_at' => now()->subDay(),
+    ]);
+    Discount::factory()->create([
+        'store_id' => $store->getKey(),
+        'code' => 'DISABLEDENDED',
+        'status' => DiscountStatus::Disabled,
+        'starts_at' => now()->subMonth(),
+        'ends_at' => now()->subDay(),
+    ]);

@@ -121,2 +140,6 @@
         ->assertDontSee('ACTIVE10')
+        ->assertDontSee('DISABLEDSOON')
+        ->set('statusFilter', 'expired')
+        ->assertSee('ENDED10')
+        ->assertDontSee('DISABLEDENDED')
         ->set('statusFilter', 'all')
@@ -230,2 +253,6 @@

+    Livewire::actingAs($user)
+        ->test(AdminDiscountForm::class, ['discount' => $draft])
+        ->assertSet('isActive', false);
+
     $expired = Discount::factory()->create([
@@ -240,2 +267,3 @@
         ->test(AdminDiscountForm::class, ['discount' => $expired])
+        ->assertSet('isActive', false)
         ->set('isActive', true)


Output: {"output":"Success. Updated the following files:\nM /Users/fabianwesner/Herd/shop/tests/Feature/Admin/DiscountManagementTest.php\n","metadata":{"exit_code":0,"duration_seconds":0.0}}


Input:
*** Begin Patch
*** Update File: /Users/fabianwesner/Herd/shop/tests/Feature/Checkout/PricingServicesTest.php
@@
 test('pricing engine applies active automatic discounts', function () {
     $store = pricingStore();
     $variant = pricingVariant($store);
     $checkout = pricingCheckout($store, $variant);
     Discount::factory()->create([
@@
         ->and($line->refresh()->line_discount_amount)->toBe(500)
         ->and($line->line_total_amount)->toBe(4500);
 });

+test('pricing engine stacks automatic discounts after explicit code discounts', function () {
+    $store = pricingStore();
+    $variant = pricingVariant($store);
+    $checkout = pricingCheckout($store, $variant);
+    Discount::factory()->create([
+        'store_id' => $store->getKey(),
+        'code' => 'SAVE10',
+        'value_type' => DiscountValueType::Percent,
+        'value_amount' => 10,
+    ]);
+    Discount::factory()->create([
+        'store_id' => $store->getKey(),
+        'type' => DiscountType::Automatic,
+        'code' => null,
+        'value_type' => DiscountValueType::Percent,
+        'value_amount' => 10,
+    ]);
+    $checkout->forceFill(['discount_code' => 'SAVE10'])->save();
+
+    $result = app(PricingEngine::class)->calculate($checkout);
+    $line = $checkout->cart->lines()->firstOrFail();
+
+    expect($result->discount)->toBe(950)
+        ->and($result->total)->toBe(4820)
+        ->and($line->refresh()->line_discount_amount)->toBe(950)
+        ->and($line->line_total_amount)->toBe(4050);
+});
+
 test('shipping and tax calculators handle matching ranges and inclusive extraction', function () {
     $store = pricingStore();
     $physicalVariant = pricingVariant($store, requiresShipping: true);
     $digitalVariant = pricingVariant($store, requiresShipping: false);
*** End Patch


Success. Updated the following files:
M /Users/fabianwesner/Herd/shop/tests/Feature/Checkout/PricingServicesTest.php

@@ -172,2 +172,30 @@

+test('pricing engine stacks automatic discounts after explicit code discounts', function () {
+    $store = pricingStore();
+    $variant = pricingVariant($store);
+    $checkout = pricingCheckout($store, $variant);
+    Discount::factory()->create([
+        'store_id' => $store->getKey(),
+        'code' => 'SAVE10',
+        'value_type' => DiscountValueType::Percent,
+        'value_amount' => 10,
+    ]);
+    Discount::factory()->create([
+        'store_id' => $store->getKey(),
+        'type' => DiscountType::Automatic,
+        'code' => null,
+        'value_type' => DiscountValueType::Percent,
+        'value_amount' => 10,
+    ]);
+    $checkout->forceFill(['discount_code' => 'SAVE10'])->save();
+
+    $result = app(PricingEngine::class)->calculate($checkout);
+    $line = $checkout->cart->lines()->firstOrFail();
+
+    expect($result->discount)->toBe(950)
+        ->and($result->total)->toBe(4820)
+        ->and($line->refresh()->line_discount_amount)->toBe(950)
+        ->and($line->line_total_amount)->toBe(4050);
+});
+
 test('shipping and tax calculators handle matching ranges and inclusive extraction', function () {


Output: {"output":"Success. Updated the following files:\nM /Users/fabianwesner/Herd/shop/tests/Feature/Checkout/PricingServicesTest.php\n","metadata":{"exit_code":0,"duration_seconds":0.0}}


Those fixes are in place with tests that cover the exact regressions: effective status filtering, draft/expired edit-state display, and discount stacking order. I’m running the focused PHP checks and formatter now.


php artisan test --compact tests/Feature/Admin/DiscountManagementTest.php


php artisan test --compact tests/Feature/Checkout/PricingServicesTest.php


Output:
Chunk ID: 7c29c9
Wall time: 0.4816 seconds
Process exited with code 0
Original token count: 30
Output:
{"result":"fixed","files":[{"path":"app\/Livewire\/Admin\/Discounts\/Index.php","fixers":["statement_indentation"]}]}


/bin/zsh
-lc
vendor/bin/pint --dirty --format agent


php artisan test --compact tests/Feature/Checkout/PricingServicesTest.php

  .....

  Tests:    5 passed (23 assertions)
  Duration: 0.40s


Output:
Chunk ID: e14b50
Wall time: 3.2980 seconds
Process exited with code 0
Original token count: 18
Output:

  ........

  Tests:    8 passed (58 assertions)
  Duration: 3.07s


Output:
Chunk ID: 651510
Wall time: 0.6309 seconds
Process exited with code 0
Original token count: 17
Output:

  .....

  Tests:    5 passed (23 assertions)
  Duration: 0.40s


php artisan test --compact tests/Feature/Admin/DiscountManagementTest.php

  ........

  Tests:    8 passed (58 assertions)
  Duration: 3.07s


The focused checks now pass with the tighter assertions: admin discounts are 8 tests / 58 assertions, pricing services are 5 tests / 23 assertions. I’m running the final full suite again and then I’ll refresh the seed once more.


Output:
Chunk ID: 300704
Wall time: 20.3030 seconds
Process exited with code 0
Original token count: 54
Output:

  ............................................................................
  .......................................................................

  Tests:    147 passed (733 assertions)
  Duration: 20.22s


php artisan migrate:fresh --seed --no-interaction