output:
Chunk ID: b515ce
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 955
Output:
<?php

namespace App\Livewire\Admin\Orders;

use App\Enums\FinancialStatus;
use App\Enums\FulfillmentStatus;
use App\Enums\OrderStatus;
use App\Models\Order;
use App\Models\Store;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Carbon;
use Livewire\Attributes\Locked;
use Livewire\Component;
use Livewire\WithPagination;
use Throwable;

class Index extends Component
{
    use WithPagination;

    #[Locked]
    public int $storeId;

    public string $search = '';

    public string $statusFilter = 'all';

    public string $financialStatusFilter = 'all';

    public string $fulfillmentStatusFilter = 'all';

    public string $dateFrom = '';

    public string $dateTo = '';

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

        abort_unless($store instanceof Store, 404);

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

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

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

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

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

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

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

    public function orders(): LengthAwarePaginator
    {
        $dateFrom = $this->parsedDate($this->dateFrom);
        $dateTo = $this->parsedDate($this->dateTo, endOfDay: true);

        return Order::withoutGlobalScopes()
            ->with('customer')
            ->withCount('lines')
            ->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('order_number', 'like', $search)
                        ->orWhere('email', 'like', $search)
                        ->orWhereHas('customer', fn (Builder $query) => $query->where('name', 'like', $search));
                });
            })
            ->when($this->statusFilter !== 'all', fn (Builder $query) => $query->where('status', $this->statusFilter))
            ->when($this->financialStatusFilter !== 'all', fn (Builder $query) => $query->where('financial_status', $this->financialStatusFilter))
            ->when($this->fulfillmentStatusFilter !== 'all', fn (Builder $query) => $query->where('fulfillment_status', $this->fulfillmentStatusFilter))
            ->when($dateFrom instanceof Carbon, fn (Builder $query) => $query->where('placed_at', '>=', $dateFrom))
            ->when($dateTo instanceof Carbon, fn (Builder $query) => $query->where('placed_at', '<=', $dateTo))
            ->latest('placed_at')
            ->latest('id')
            ->paginate(20);
    }

    public function render(): mixed
    {
        return view('livewire.admin.orders.index', [
            'orders' => $this->orders(),
            'statuses' => OrderStatus::cases(),
            'financialStatuses' => FinancialStatus::cases(),
            'fulfillmentStatuses' => FulfillmentStatus::cases(),
        ])->layout('layouts.app', [
            'title' => __('Orders'),
        ]);
    }

    private function parsedDate(string $value, bool $endOfDay = false): ?Carbon
    {
        if ($value === '') {
            return null;
        }

        try {
            $date = Carbon::parse($value);

            return $endOfDay ? $date->endOfDay() : $date->startOfDay();
        } catch (Throwable) {
            return null;
        }
    }
}


command: sed -n '1,320p' app/Livewire/Admin/Orders/Show.php

Show.php

type: read

aggregated_output:
<?php

namespace App\Livewire\Admin\Orders;

use App\Enums\RefundStatus;
use App\Exceptions\InvalidFulfillmentOperationException;
use App\Exceptions\InvalidOrderOperationException;
use App\Exceptions\InvalidRefundOperationException;
use App\Models\Fulfillment;
use App\Models\Order;
use App\Models\OrderLine;
use App\Models\Refund;
use App\Models\Store;
use App\Services\FulfillmentService;
use App\Services\OrderService;
use App\Services\RefundService;
use App\Support\Money;
use Illuminate\Validation\ValidationException;
use Livewire\Attributes\Locked;
use Livewire\Component;

class Show extends Component
{
    #[Locked]
    public int $storeId;

    #[Locked]
    public int $orderId;

    public string $refundAmount = '';

    public string $refundReason = '';

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

    public string $trackingCompany = '';

    public string $trackingNumber = '';

    public string $trackingUrl = '';

    public string $actionMessage = '';

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

        abort_unless($store instanceof Store, 404);

        $order = Order::withoutGlobalScopes()
            ->where('store_id', $store->getKey())
            ->whereKey($order->getKey())
            ->first();

        abort_unless($order instanceof Order, 404);

        $this->storeId = $store->getKey();
        $this->orderId = $order->getKey();
        $this->resetFulfillmentLineQuantities($this->order());
    }

    public function confirmBankTransferPayment(OrderService $orders): void
    {
        try {
            $orders->confirmBankTransferPayment($this->order());
            $this->resetFulfillmentLineQuantities($this->order());
            $this->actionMessage = __('Payment confirmed');
            $this->dispatch('toast', type: 'success', message: __('Payment confirmed'));
        } catch (InvalidOrderOperationException $exception) {
            throw ValidationException::withMessages([
                'orderAction' => $exception->getMessage(),
            ]);
        }
    }

    public function processRefund(RefundService $refunds): void
    {
        $this->validate([
            'refundAmount' => ['nullable', 'numeric', 'min:0.01'],
            'refundReason' => ['nullable', 'string', 'max:500'],
        ]);

        $request = [
            'reason' => $this->refundReason !== '' ? $this->refundReason : null,
        ];

        if ($this->refundAmount !== '') {
            $request['amount'] = Money::fromDecimalString($this->refundAmount);
        }

        try {
            $refunds->process($this->order(), $request);
            $this->refundAmount = '';
            $this->refundReason = '';
            $this->actionMessage = __('Refund processed');
            $this->modal('refund-order')->close();
            $this->dispatch('toast', type: 'success', message: __('Refund processed'));
        } catch (InvalidRefundOperationException $exception) {
            throw ValidationException::withMessages([
                'refundAmount' => $exception->getMessage(),
            ]);
        }
    }

    public function createFulfillment(FulfillmentService $fulfillments): void
    {
        $this->validate([
            'fulfillmentLineQuantities' => ['array'],
            'trackingCompany' => ['nullable', 'string', 'max:255'],
            'trackingNumber' => ['nullable', 'string', 'max:255'],
            'trackingUrl' => ['nullable', 'url', 'max:2048'],
        ]);

        $lines = collect($this->fulfillmentLineQuantities)
            ->mapWithKeys(fn (mixed $quantity, int|string $lineId): array => [(int) $lineId => (int) $quantity])
            ->filter(fn (int $quantity): bool => $quantity > 0)
            ->all();

        if ($lines === []) {
            throw ValidationException::withMessages([
                'fulfillment' => __('At least one fulfillment line is required.'),
            ]);
        }

        try {
            $fulfillments->create($this->order(), $lines, [
                'tracking_company' => $this->trackingCompany !== '' ? $this->trackingCompany : null,
                'tracking_number' => $this->trackingNumber !== '' ? $this->trackingNumber : null,
                'tracking_url' => $this->trackingUrl !== '' ? $this->trackingUrl : null,
            ]);

            $this->trackingCompany = '';
            $this->trackingNumber = '';
            $this->trackingUrl = '';
            $this->resetFulfillmentLineQuantities($this->order());
            $this->actionMessage = __('Fulfillment created');
            $this->modal('fulfillment-order')->close();
            $this->dispatch('toast', type: 'success', message: __('Fulfillment created'));
        } catch (InvalidFulfillmentOperationException $exception) {
            throw ValidationException::withMessages([
                'fulfillment' => $exception->getMessage(),
            ]);
        }
    }

    public function markFulfillmentShipped(int $fulfillmentId, FulfillmentService $fulfillments): void
    {
        try {
            $fulfillments->markShipped($this->fulfillment($fulfillmentId));
            $this->actionMessage = __('Fulfillment marked as shipped');
            $this->dispatch('toast', type: 'success', message: __('Fulfillment marked as shipped'));
        } catch (InvalidFulfillmentOperationException $exception) {
            throw ValidationException::withMessages([
                'fulfillment' => $exception->getMessage(),
            ]);
        }
    }

    public function markFulfillmentDelivered(int $fulfillmentId, FulfillmentService $fulfillments): void
    {
        try {
            $fulfillments->markDelivered($this->fulfillment($fulfillmentId));
            $this->actionMessage = __('Fulfillment marked as delivered');
            $this->dispatch('toast', type: 'success', message: __('Fulfillment marked as delivered'));
        } catch (InvalidFulfillmentOperationException $exception) {
            throw ValidationException::withMessages([
                'fulfillment' => $exception->getMessage(),
            ]);
        }
    }

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

        return view('livewire.admin.orders.show', [
            'order' => $order,
            'remainingFulfillmentQuantities' => $this->remainingFulfillmentQuantities($order),
            'refundableAmount' => $this->refundableAmount($order),
        ])->layout('layouts.app', [
            'title' => $order->order_number,
        ]);
    }

    private function order(): Order
    {
        return Order::withoutGlobalScopes()
            ->with([
                'customer',
                'lines.fulfillmentLines',
                'payments',
                'refunds',
                'fulfillments.lines.orderLine',
            ])
            ->where('store_id', $this->storeId)
            ->whereKey($this->orderId)
            ->firstOrFail();
    }

    private function fulfillment(int $fulfillmentId): Fulfillment
    {
        $fulfillment = $this->order()
            ->fulfillments
            ->firstWhere('id', $fulfillmentId);

        abort_unless($fulfillment instanceof Fulfillment, 404);

        return $fulfillment;
    }

    /**
     * @return array<int, int>
     */
    private function remainingFulfillmentQuantities(Order $order): array
    {
        return $order->lines
            ->mapWithKeys(function (OrderLine $line): array {
                $fulfilled = $line->fulfillmentLines->sum('quantity');

                return [$line->getKey() => max(0, $line->quantity - $fulfilled)];
            })
            ->all();
    }

    private function resetFulfillmentLineQuantities(Order $order): void
    {
        $this->fulfillmentLineQuantities = $this->remainingFulfillmentQuantities($order);
    }

    private function refundableAmount(Order $order): int
    {
        $refunded = $order->refunds
            ->reject(fn (Refund $refund): bool => $refund->status === RefundStatus::Failed)
            ->sum('amount');

        return max(0, $order->total_amount - $refunded);
    }
}

status: completed


output:
Chunk ID: 290315
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 2041
Output:
<?php

namespace App\Livewire\Admin\Orders;

use App\Enums\RefundStatus;
use App\Exceptions\InvalidFulfillmentOperationException;
use App\Exceptions\InvalidOrderOperationException;
use App\Exceptions\InvalidRefundOperationException;
use App\Models\Fulfillment;
use App\Models\Order;
use App\Models\OrderLine;
use App\Models\Refund;
use App\Models\Store;
use App\Services\FulfillmentService;
use App\Services\OrderService;
use App\Services\RefundService;
use App\Support\Money;
use Illuminate\Validation\ValidationException;
use Livewire\Attributes\Locked;
use Livewire\Component;

class Show extends Component
{
    #[Locked]
    public int $storeId;

    #[Locked]
    public int $orderId;

    public string $refundAmount = '';

    public string $refundReason = '';

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

    public string $trackingCompany = '';

    public string $trackingNumber = '';

    public string $trackingUrl = '';

    public string $actionMessage = '';

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

        abort_unless($store instanceof Store, 404);

        $order = Order::withoutGlobalScopes()
            ->where('store_id', $store->getKey())
            ->whereKey($order->getKey())
            ->first();

        abort_unless($order instanceof Order, 404);

        $this->storeId = $store->getKey();
        $this->orderId = $order->getKey();
        $this->resetFulfillmentLineQuantities($this->order());
    }

    public function confirmBankTransferPayment(OrderService $orders): void
    {
        try {
            $orders->confirmBankTransferPayment($this->order());
            $this->resetFulfillmentLineQuantities($this->order());
            $this->actionMessage = __('Payment confirmed');
            $this->dispatch('toast', type: 'success', message: __('Payment confirmed'));
        } catch (InvalidOrderOperationException $exception) {
            throw ValidationException::withMessages([
                'orderAction' => $exception->getMessage(),
            ]);
        }
    }

    public function processRefund(RefundService $refunds): void
    {
        $this->validate([
            'refundAmount' => ['nullable', 'numeric', 'min:0.01'],
            'refundReason' => ['nullable', 'string', 'max:500'],
        ]);

        $request = [
            'reason' => $this->refundReason !== '' ? $this->refundReason : null,
        ];

        if ($this->refundAmount !== '') {
            $request['amount'] = Money::fromDecimalString($this->refundAmount);
        }

        try {
            $refunds->process($this->order(), $request);
            $this->refundAmount = '';
            $this->refundReason = '';
            $this->actionMessage = __('Refund processed');
            $this->modal('refund-order')->close();
            $this->dispatch('toast', type: 'success', message: __('Refund processed'));
        } catch (InvalidRefundOperationException $exception) {
            throw ValidationException::withMessages([
                'refundAmount' => $exception->getMessage(),
            ]);
        }
    }

    public function createFulfillment(FulfillmentService $fulfillments): void
    {
        $this->validate([
            'fulfillmentLineQuantities' => ['array'],
            'trackingCompany' => ['nullable', 'string', 'max:255'],
            'trackingNumber' => ['nullable', 'string', 'max:255'],
            'trackingUrl' => ['nullable', 'url', 'max:2048'],
        ]);

        $lines = collect($this->fulfillmentLineQuantities)
            ->mapWithKeys(fn (mixed $quantity, int|string $lineId): array => [(int) $lineId => (int) $quantity])
            ->filter(fn (int $quantity): bool => $quantity > 0)
            ->all();

        if ($lines === []) {
            throw ValidationException::withMessages([
                'fulfillment' => __('At least one fulfillment line is required.'),
            ]);
        }

        try {
            $fulfillments->create($this->order(), $lines, [
                'tracking_company' => $this->trackingCompany !== '' ? $this->trackingCompany : null,
                'tracking_number' => $this->trackingNumber !== '' ? $this->trackingNumber : null,
                'tracking_url' => $this->trackingUrl !== '' ? $this->trackingUrl : null,
            ]);

            $this->trackingCompany = '';
            $this->trackingNumber = '';
            $this->trackingUrl = '';
            $this->resetFulfillmentLineQuantities($this->order());
            $this->actionMessage = __('Fulfillment created');
            $this->modal('fulfillment-order')->close();
            $this->dispatch('toast', type: 'success', message: __('Fulfillment created'));
        } catch (InvalidFulfillmentOperationException $exception) {
            throw ValidationException::withMessages([
                'fulfillment' => $exception->getMessage(),
            ]);
        }
    }

    public function markFulfillmentShipped(int $fulfillmentId, FulfillmentService $fulfillments): void
    {
        try {
            $fulfillments->markShipped($this->fulfillment($fulfillmentId));
            $this->actionMessage = __('Fulfillment marked as shipped');
            $this->dispatch('toast', type: 'success', message: __('Fulfillment marked as shipped'));
        } catch (InvalidFulfillmentOperationException $exception) {
            throw ValidationException::withMessages([
                'fulfillment' => $exception->getMessage(),
            ]);
        }
    }

    public function markFulfillmentDelivered(int $fulfillmentId, FulfillmentService $fulfillments): void
    {
        try {
            $fulfillments->markDelivered($this->fulfillment($fulfillmentId));
            $this->actionMessage = __('Fulfillment marked as delivered');
            $this->dispatch('toast', type: 'success', message: __('Fulfillment marked as delivered'));
        } catch (InvalidFulfillmentOperationException $exception) {
            throw ValidationException::withMessages([
                'fulfillment' => $exception->getMessage(),
            ]);
        }
    }

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

        return view('livewire.admin.orders.show', [
            'order' => $order,
            'remainingFulfillmentQuantities' => $this->remainingFulfillmentQuantities($order),
            'refundableAmount' => $this->refundableAmount($order),
        ])->layout('layouts.app', [
            'title' => $order->order_number,
        ]);
    }

    private function order(): Order
    {
        return Order::withoutGlobalScopes()
            ->with([
                'customer',
                'lines.fulfillmentLines',
                'payments',
                'refunds',
                'fulfillments.lines.orderLine',
            ])
            ->where('store_id', $this->storeId)
            ->whereKey($this->orderId)
            ->firstOrFail();
    }

    private function fulfillment(int $fulfillmentId): Fulfillment
    {
        $fulfillment = $this->order()
            ->fulfillments
            ->firstWhere('id', $fulfillmentId);

        abort_unless($fulfillment instanceof Fulfillment, 404);

        return $fulfillment;
    }

    /**
     * @return array<int, int>
     */
    private function remainingFulfillmentQuantities(Order $order): array
    {
        return $order->lines
            ->mapWithKeys(function (OrderLine $line): array {
                $fulfilled = $line->fulfillmentLines->sum('quantity');

                return [$line->getKey() => max(0, $line->quantity - $fulfilled)];
            })
            ->all();
    }

    private function resetFulfillmentLineQuantities(Order $order): void
    {
        $this->fulfillmentLineQuantities = $this->remainingFulfillmentQuantities($order);
    }

    private function refundableAmount(Order $order): int
    {
        $refunded = $order->refunds
            ->reject(fn (Refund $refund): bool => $refund->status === RefundStatus::Failed)
            ->sum('amount');

        return max(0, $order->total_amount - $refunded);
    }
}


command: sed -n '1,220p' app/Livewire/Admin/Customers/Show.php

aggregated_output:
<?php

namespace App\Livewire\Admin\Customers;

use App\Models\Customer;
use App\Models\CustomerAddress;
use App\Models\Order;
use App\Models\Store;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\DB;
use Livewire\Attributes\Locked;
use Livewire\Component;
use Livewire\WithPagination;

class Show extends Component
{
    use WithPagination;

    #[Locked]
    public int $storeId;

    #[Locked]
    public int $customerId;

    public ?int $editingAddressId = null;

    public string $addressLabel = '';

    /**
     * @var array{first_name: string, last_name: string, address1: string, address2: string, city: string, province_code: string, country: string, postal_code: string}
     */
    public array $addressJson = [
        'first_name' => '',
        'last_name' => '',
        'address1' => '',
        'address2' => '',
        'city' => '',
        'province_code' => '',
        'country' => 'DE',
        'postal_code' => '',
    ];

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

        abort_unless($store instanceof Store, 404);

        $customer = Customer::withoutGlobalScopes()
            ->where('store_id', $store->getKey())
            ->whereKey($customer->getKey())
            ->first();

        abort_unless($customer instanceof Customer, 404);

        $this->storeId = $store->getKey();
        $this->customerId = $customer->getKey();
    }

    public function openAddressForm(?int $addressId = null): void
    {
        $this->editingAddressId = $addressId;

        if ($addressId) {
            $address = $this->address($addressId);
            $this->addressLabel = (string) $address->label;
            $this->addressJson = array_merge($this->emptyAddressJson(), $address->address_json ?? []);
        } else {
            $this->resetAddressForm();
        }

        $this->modal('address-form')->show();
    }

    public function saveAddress(): void
    {
        $this->validate([
            'addressLabel' => ['nullable', 'string', 'max:255'],
            'addressJson.first_name' => ['nullable', 'string', 'max:255'],
            'addressJson.last_name' => ['nullable', 'string', 'max:255'],
            'addressJson.address1' => ['required', 'string', 'max:255'],
            'addressJson.address2' => ['nullable', 'string', 'max:255'],
            'addressJson.city' => ['required', 'string', 'max:255'],
            'addressJson.province_code' => ['nullable', 'string', 'max:255'],
            'addressJson.country' => ['required', 'string', 'size:2'],
            'addressJson.postal_code' => ['required', 'string', 'max:32'],
        ]);

        $address = $this->editingAddressId
            ? $this->address($this->editingAddressId)
            : new CustomerAddress(['customer_id' => $this->customerId]);

        $address->fill([
            'label' => $this->addressLabel !== '' ? $this->addressLabel : null,
            'address_json' => $this->addressJson,
            'is_default' => $address->exists ? $address->is_default : ! $this->customer()->addresses()->exists(),
        ]);
        $address->save();

        $this->resetAddressForm();
        $this->modal('address-form')->close();
        $this->dispatch('toast', type: 'success', message: __('Address saved'));
    }

    public function deleteAddress(int $addressId): void
    {
        $address = $this->address($addressId);
        $wasDefault = $address->is_default;
        $address->delete();

        if ($wasDefault) {
            $this->setFirstAddressAsDefault();
        }

        $this->dispatch('toast', type: 'success', message: __('Address deleted'));
    }

    public function setDefaultAddress(int $addressId): void
    {
        $address = $this->address($addressId);

        DB::transaction(function () use ($address): void {
            CustomerAddress::query()
                ->where('customer_id', $this->customerId)
                ->update(['is_default' => false]);

            $address->forceFill(['is_default' => true])->save();
        });

        $this->dispatch('toast', type: 'success', message: __('Default address updated'));
    }

    public function orders(): LengthAwarePaginator
    {
        return Order::withoutGlobalScopes()
            ->where('store_id', $this->storeId)
            ->where('customer_id', $this->customerId)
            ->latest('placed_at')
            ->latest('id')
            ->paginate(10);
    }

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

        return view('livewire.admin.customers.show', [
            'customer' => $customer,
            'orders' => $this->orders(),
        ])->layout('layouts.app', [
            'title' => $customer->name ?: $customer->email,
        ]);
    }

    private function customer(): Customer
    {
        return Customer::withoutGlobalScopes()
            ->with(['addresses' => fn ($query) => $query->orderByDesc('is_default')->orderBy('id')])
            ->where('store_id', $this->storeId)
            ->whereKey($this->customerId)
            ->firstOrFail();
    }

    private function address(int $addressId): CustomerAddress
    {
        return CustomerAddress::query()
            ->where('customer_id', $this->customerId)
            ->whereKey($addressId)
            ->firstOrFail();
    }

    private function setFirstAddressAsDefault(): void
    {
        $nextAddress = CustomerAddress::query()
            ->where('customer_id', $this->customerId)
            ->oldest('id')
            ->first();

        if ($nextAddress instanceof CustomerAddress) {
            $nextAddress->forceFill(['is_default' => true])->save();
        }
    }

    private function resetAddressForm(): void
    {
        $this->editingAddressId = null;
        $this->addressLabel = '';
        $this->addressJson = $this->emptyAddressJson();
    }

    /**
     * @return array{first_name: string, last_name: string, address1: string, address2: string, city: string, province_code: string, country: string, postal_code: string}
     */
    private function emptyAddressJson(): array
    {
        return [
            'first_name' => '',
            'last_name' => '',
            'address1' => '',
            'address2' => '',
            'city' => '',
            'province_code' => '',
            'country' => 'DE',
            'postal_code' => '',
        ];
    }
}


output:
Chunk ID: fed36b
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 1610
Output:
<?php

namespace App\Livewire\Admin\Customers;

use App\Models\Customer;
use App\Models\CustomerAddress;
use App\Models\Order;
use App\Models\Store;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Support\Facades\DB;
use Livewire\Attributes\Locked;
use Livewire\Component;
use Livewire\WithPagination;

class Show extends Component
{
    use WithPagination;

    #[Locked]
    public int $storeId;

    #[Locked]
    public int $customerId;

    public ?int $editingAddressId = null;

    public string $addressLabel = '';

    /**
     * @var array{first_name: string, last_name: string, address1: string, address2: string, city: string, province_code: string, country: string, postal_code: string}
     */
    public array $addressJson = [
        'first_name' => '',
        'last_name' => '',
        'address1' => '',
        'address2' => '',
        'city' => '',
        'province_code' => '',
        'country' => 'DE',
        'postal_code' => '',
    ];

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

        abort_unless($store instanceof Store, 404);

        $customer = Customer::withoutGlobalScopes()
            ->where('store_id', $store->getKey())
            ->whereKey($customer->getKey())
            ->first();

        abort_unless($customer instanceof Customer, 404);

        $this->storeId = $store->getKey();
        $this->customerId = $customer->getKey();
    }

    public function openAddressForm(?int $addressId = null): void
    {
        $this->editingAddressId = $addressId;

        if ($addressId) {
            $address = $this->address($addressId);
            $this->addressLabel = (string) $address->label;
            $this->addressJson = array_merge($this->emptyAddressJson(), $address->address_json ?? []);
        } else {
            $this->resetAddressForm();
        }

        $this->modal('address-form')->show();
    }

    public function saveAddress(): void
    {
        $this->validate([
            'addressLabel' => ['nullable', 'string', 'max:255'],
            'addressJson.first_name' => ['nullable', 'string', 'max:255'],
            'addressJson.last_name' => ['nullable', 'string', 'max:255'],
            'addressJson.address1' => ['required', 'string', 'max:255'],
            'addressJson.address2' => ['nullable', 'string', 'max:255'],
            'addressJson.city' => ['required', 'string', 'max:255'],
            'addressJson.province_code' => ['nullable', 'string', 'max:255'],
            'addressJson.country' => ['required', 'string', 'size:2'],
            'addressJson.postal_code' => ['required', 'string', 'max:32'],
        ]);

        $address = $this->editingAddressId
            ? $this->address($this->editingAddressId)
            : new CustomerAddress(['customer_id' => $this->customerId]);

        $address->fill([
            'label' => $this->addressLabel !== '' ? $this->addressLabel : null,
            'address_json' => $this->addressJson,
            'is_default' => $address->exists ? $address->is_default : ! $this->customer()->addresses()->exists(),
        ]);
        $address->save();

        $this->resetAddressForm();
        $this->modal('address-form')->close();
        $this->dispatch('toast', type: 'success', message: __('Address saved'));
    }

    public function deleteAddress(int $addressId): void
    {
        $address = $this->address($addressId);
        $wasDefault = $address->is_default;
        $address->delete();

        if ($wasDefault) {
            $this->setFirstAddressAsDefault();
        }

        $this->dispatch('toast', type: 'success', message: __('Address deleted'));
    }

    public function setDefaultAddress(int $addressId): void
    {
        $address = $this->address($addressId);

        DB::transaction(function () use ($address): void {
            CustomerAddress::query()
                ->where('customer_id', $this->customerId)
                ->update(['is_default' => false]);

            $address->forceFill(['is_default' => true])->save();
        });

        $this->dispatch('toast', type: 'success', message: __('Default address updated'));
    }

    public function orders(): LengthAwarePaginator
    {
        return Order::withoutGlobalScopes()
            ->where('store_id', $this->storeId)
            ->where('customer_id', $this->customerId)
            ->latest('placed_at')
            ->latest('id')
            ->paginate(10);
    }

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

        return view('livewire.admin.customers.show', [
            'customer' => $customer,
            'orders' => $this->orders(),
        ])->layout('layouts.app', [
            'title' => $customer->name ?: $customer->email,
        ]);
    }

    private function customer(): Customer
    {
        return Customer::withoutGlobalScopes()
            ->with(['addresses' => fn ($query) => $query->orderByDesc('is_default')->orderBy('id')])
            ->where('store_id', $this->storeId)
            ->whereKey($this->customerId)
            ->firstOrFail();
    }

    private function address(int $addressId): CustomerAddress
    {
        return CustomerAddress::query()
            ->where('customer_id', $this->customerId)
            ->whereKey($addressId)
            ->firstOrFail();
    }

    private function setFirstAddressAsDefault(): void
    {
        $nextAddress = CustomerAddress::query()
            ->where('customer_id', $this->customerId)
            ->oldest('id')
            ->first();

        if ($nextAddress instanceof CustomerAddress) {
            $nextAddress->forceFill(['is_default' => true])->save();
        }
    }

    private function resetAddressForm(): void
    {
        $this->editingAddressId = null;
        $this->addressLabel = '';
        $this->addressJson = $this->emptyAddressJson();
    }

    /**
     * @return array{first_name: string, last_name: string, address1: string, address2: string, city: string, province_code: string, country: string, postal_code: string}
     */
    private function emptyAddressJson(): array
    {
        return [
            'first_name' => '',
            'last_name' => '',
            'address1' => '',
            'address2' => '',
            'city' => '',
            'province_code' => '',
            'country' => 'DE',
            'postal_code' => '',
        ];
    }
}


command: rg -n "orderBy|latest|paginate|placed_at" app/Livewire/Storefront/Account/Orders app/Livewire/Admin/Orders app/Livewire/Admin/Customers -S

type: search

cmd: rg -n 'orderBy|latest|paginate|placed_at' app/Livewire/Storefront/Account/Orders app/Livewire/Admin/Orders app/Livewire/Admin/Customers -S

path: Orders

aggregated_output:
app/Livewire/Admin/Customers/Index.php:54:            ->latest('created_at')
app/Livewire/Admin/Customers/Index.php:55:            ->paginate(20);
app/Livewire/Storefront/Account/Orders/Index.php:50:            ->latest('placed_at')
app/Livewire/Storefront/Account/Orders/Index.php:51:            ->latest('id')
app/Livewire/Admin/Orders/Index.php:98:            ->when($dateFrom instanceof Carbon, fn (Builder $query) => $query->where('placed_at', '>=', $dateFrom))
app/Livewire/Admin/Orders/Index.php:99:            ->when($dateTo instanceof Carbon, fn (Builder $query) => $query->where('placed_at', '<=', $dateTo))
app/Livewire/Admin/Orders/Index.php:100:            ->latest('placed_at')
app/Livewire/Admin/Orders/Index.php:101:            ->latest('id')
app/Livewire/Admin/Orders/Index.php:102:            ->paginate(20);
app/Livewire/Admin/Customers/Show.php:138:            ->latest('placed_at')
app/Livewire/Admin/Customers/Show.php:139:            ->latest('id')
app/Livewire/Admin/Customers/Show.php:140:            ->paginate(10);
app/Livewire/Admin/Customers/Show.php:158:            ->with(['addresses' => fn ($query) => $query->orderByDesc('is_default')->orderBy('id')])


output:
Chunk ID: f039a1
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 297
Output:
app/Livewire/Admin/Customers/Index.php:54:            ->latest('created_at')
app/Livewire/Admin/Customers/Index.php:55:            ->paginate(20);
app/Livewire/Storefront/Account/Orders/Index.php:50:            ->latest('placed_at')
app/Livewire/Storefront/Account/Orders/Index.php:51:            ->latest('id')
app/Livewire/Admin/Orders/Index.php:98:            ->when($dateFrom instanceof Carbon, fn (Builder $query) => $query->where('placed_at', '>=', $dateFrom))
app/Livewire/Admin/Orders/Index.php:99:            ->when($dateTo instanceof Carbon, fn (Builder $query) => $query->where('placed_at', '<=', $dateTo))
app/Livewire/Admin/Orders/Index.php:100:            ->latest('placed_at')
app/Livewire/Admin/Orders/Index.php:101:            ->latest('id')
app/Livewire/Admin/Orders/Index.php:102:            ->paginate(20);
app/Livewire/Admin/Customers/Show.php:138:            ->latest('placed_at')
app/Livewire/Admin/Customers/Show.php:139:            ->latest('id')
app/Livewire/Admin/Customers/Show.php:140:            ->paginate(10);
app/Livewire/Admin/Customers/Show.php:158:            ->with(['addresses' => fn ($query) => $query->orderByDesc('is_default')->orderBy('id')])


cmd: sed -n '1,280p' app/Livewire/Admin/Dashboard.php


cmd: sed -n '1,260p' resources/views/livewire/admin/dashboard.blade.php


cmd: rg -n "#1001|#1002|#1004|#1005|Order::withoutGlobalScopes\(\)->count\(\)|firstOrFail\(\)" tests -S


command: sed -n '1,280p' app/Livewire/Admin/Dashboard.php

aggregated_output:
<?php

namespace App\Livewire\Admin;

use App\Enums\FinancialStatus;
use App\Models\Cart;
use App\Models\Checkout;
use App\Models\Order;
use App\Models\OrderLine;
use App\Models\Store;
use App\Support\Money;
use Carbon\CarbonInterface;
use Carbon\CarbonPeriod;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Carbon;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Locked;
use Livewire\Component;
use Throwable;

class Dashboard extends Component
{
    #[Locked]
    public int $storeId;

    public string $storeCurrency = 'EUR';

    public string $dateRange = 'last_30_days';

    public ?string $customStartDate = null;

    public ?string $customEndDate = null;

    public int $totalSales = 0;

    public int $ordersCount = 0;

    public int $averageOrderValue = 0;

    public int $visitorsCount = 0;

    public float $salesChange = 0.0;

    public float $ordersChange = 0.0;

    public float $aovChange = 0.0;

    public float $visitorsChange = 0.0;

    /**
     * @var list<array{date: string, label: string, count: int}>
     */
    public array $ordersChartData = [];

    public int $maxOrdersChartCount = 1;

    /**
     * @var list<array{title: string, units_sold: int, revenue: int}>
     */
    public array $topProducts = [];

    /**
     * @var array{visits: int, add_to_cart: int, checkout_started: int, checkout_completed: int}
     */
    public array $funnelData = [
        'visits' => 0,
        'add_to_cart' => 0,
        'checkout_started' => 0,
        'checkout_completed' => 0,
    ];

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

        abort_unless($store instanceof Store, 404);

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

        $this->loadKpis();
    }

    public function updatedDateRange(): void
    {
        $this->loadKpis();
    }

    public function updatedCustomStartDate(): void
    {
        if ($this->dateRange === 'custom') {
            $this->loadKpis();
        }
    }

    public function updatedCustomEndDate(): void
    {
        if ($this->dateRange === 'custom') {
            $this->loadKpis();
        }
    }

    public function loadKpis(): void
    {
        [$start, $end] = $this->currentRange();
        [$previousStart, $previousEnd] = $this->previousRange($start, $end);

        $this->ordersCount = $this->ordersBetween($start, $end)->count();
        $previousOrdersCount = $this->ordersBetween($previousStart, $previousEnd)->count();

        $this->totalSales = (int) $this->revenueOrdersBetween($start, $end)->sum('total_amount');
        $previousTotalSales = (int) $this->revenueOrdersBetween($previousStart, $previousEnd)->sum('total_amount');

        $revenueOrdersCount = $this->revenueOrdersBetween($start, $end)->count();
        $previousRevenueOrdersCount = $this->revenueOrdersBetween($previousStart, $previousEnd)->count();

        $this->averageOrderValue = $revenueOrdersCount > 0 ? intdiv($this->totalSales, $revenueOrdersCount) : 0;
        $previousAverageOrderValue = $previousRevenueOrdersCount > 0 ? intdiv($previousTotalSales, $previousRevenueOrdersCount) : 0;

        $this->visitorsCount = 0;
        $this->salesChange = $this->percentChange($this->totalSales, $previousTotalSales);
        $this->ordersChange = $this->percentChange($this->ordersCount, $previousOrdersCount);
        $this->aovChange = $this->percentChange($this->averageOrderValue, $previousAverageOrderValue);
        $this->visitorsChange = 0.0;

        $this->loadChart();
        $this->loadTopProducts();
        $this->loadFunnel();
    }

    public function loadChart(): void
    {
        [$start, $end] = $this->currentRange();

        $counts = $this->ordersBetween($start, $end)
            ->selectRaw('date(placed_at) as order_date, count(*) as aggregate')
            ->groupBy('order_date')
            ->pluck('aggregate', 'order_date');

        $this->ordersChartData = collect(CarbonPeriod::create($start->copy()->startOfDay(), '1 day', $end->copy()->startOfDay()))
            ->map(fn (CarbonInterface $date): array => [
                'date' => $date->toDateString(),
                'label' => $date->format('M j'),
                'count' => (int) ($counts[$date->toDateString()] ?? 0),
            ])
            ->values()
            ->all();

        $this->maxOrdersChartCount = max(1, max(array_column($this->ordersChartData, 'count') ?: [0]));
    }

    public function loadTopProducts(): void
    {
        [$start, $end] = $this->currentRange();

        $this->topProducts = OrderLine::query()
            ->selectRaw('order_lines.title_snapshot as title, sum(order_lines.quantity) as units_sold, sum(order_lines.total_amount) as revenue')
            ->join('orders', 'orders.id', '=', 'order_lines.order_id')
            ->where('orders.store_id', $this->storeId)
            ->whereBetween('orders.placed_at', [$start, $end])
            ->whereIn('orders.financial_status', $this->revenueStatuses())
            ->groupBy('order_lines.product_id', 'order_lines.title_snapshot')
            ->orderByDesc('revenue')
            ->limit(5)
            ->get()
            ->map(fn (OrderLine $line): array => [
                'title' => (string) $line->title,
                'units_sold' => (int) $line->units_sold,
                'revenue' => (int) $line->revenue,
            ])
            ->all();
    }

    public function loadFunnel(): void
    {
        [$start, $end] = $this->currentRange();

        $this->funnelData = [
            'visits' => 0,
            'add_to_cart' => Cart::withoutGlobalScopes()
                ->where('store_id', $this->storeId)
                ->whereBetween('created_at', [$start, $end])
                ->count(),
            'checkout_started' => Checkout::withoutGlobalScopes()
                ->where('store_id', $this->storeId)
                ->whereBetween('created_at', [$start, $end])
                ->count(),
            'checkout_completed' => $this->ordersCount,
        ];
    }

    #[Computed]
    public function formattedTotalSales(): string
    {
        return Money::format($this->totalSales, $this->storeCurrency);
    }

    #[Computed]
    public function formattedAov(): string
    {
        return Money::format($this->averageOrderValue, $this->storeCurrency);
    }

    public function render(): mixed
    {
        return view('livewire.admin.dashboard')->layout('layouts.app', [
            'title' => __('Dashboard'),
        ]);
    }

    /**
     * @return array{0: CarbonInterface, 1: CarbonInterface}
     */
    private function currentRange(): array
    {
        return match ($this->dateRange) {
            'today' => [now()->startOfDay(), now()->endOfDay()],
            'last_7_days' => [now()->subDays(6)->startOfDay(), now()->endOfDay()],
            'custom' => $this->customRange() ?? [now()->subDays(29)->startOfDay(), now()->endOfDay()],
            default => [now()->subDays(29)->startOfDay(), now()->endOfDay()],
        };
    }

    /**
     * @return array{0: CarbonInterface, 1: CarbonInterface}
     */
    private function previousRange(CarbonInterface $start, CarbonInterface $end): array
    {
        $days = max(1, $start->copy()->startOfDay()->diffInDays($end->copy()->startOfDay()) + 1);
        $previousEnd = $start->copy()->subSecond();

        return [$start->copy()->subDays($days)->startOfDay(), $previousEnd];
    }

    /**
     * @return array{0: CarbonInterface, 1: CarbonInterface}|null
     */
    private function customRange(): ?array
    {
        if (! $this->customStartDate || ! $this->customEndDate) {
            return null;
        }

        try {
            $start = Carbon::parse($this->customStartDate)->startOfDay();
            $end = Carbon::parse($this->customEndDate)->endOfDay();
        } catch (Throwable) {
            return null;
        }

        if ($end->lessThan($start)) {
            return [$end->startOfDay(), $start->endOfDay()];
        }

        return [$start, $end];
    }

    /**
     * @return Builder<Order>
     */
    private function ordersBetween(CarbonInterface $start, CarbonInterface $end): Builder
    {
        return Order::withoutGlobalScopes()
            ->where('store_id', $this->storeId)
            ->whereBetween('placed_at', [$start, $end]);
    }

    /**
     * @return Builder<Order>
     */
    private function revenueOrdersBetween(CarbonInterface $start, CarbonInterface $end): Builder
    {
        return $this->ordersBetween($start, $end)
            ->whereIn('financial_status', $this->revenueStatuses());
    }

    /**
     * @return list<string>
     */
    private function revenueStatuses(): array


command: sed -n '1,260p' resources/views/livewire/admin/dashboard.blade.php

aggregated_output:
            <flux:heading size="xl">Dashboard</flux:heading>
            <flux:text class="mt-1">Sales, orders, and product movement for the selected store.</flux:text>

            <flux:select wire:model.live="dateRange" aria-label="Date range">
                <flux:select.option value="today">Today</flux:select.option>
                <flux:select.option value="last_7_days">Last 7 days</flux:select.option>
                <flux:select.option value="last_30_days">Last 30 days</flux:select.option>
                <flux:select.option value="custom">Custom</flux:select.option>
            </flux:select>

            <flux:input type="date" wire:model.live="customStartDate" :disabled="$dateRange !== 'custom'" aria-label="Custom range start" />
            <flux:input type="date" wire:model.live="customEndDate" :disabled="$dateRange !== 'custom'" aria-label="Custom range end" />

        @foreach ([
            ['label' => 'Total sales', 'value' => $this->formattedTotalSales, 'change' => $salesChange, 'icon' => 'banknotes'],
            ['label' => 'Orders', 'value' => number_format($ordersCount), 'change' => $ordersChange, 'icon' => 'shopping-bag'],
            ['label' => 'Average order', 'value' => $this->formattedAov, 'change' => $aovChange, 'icon' => 'receipt-percent'],
            ['label' => 'Visitors', 'value' => number_format($visitorsCount), 'change' => $visitorsChange, 'icon' => 'users'],
        ] as $metric)
            @php
                $change = (float) $metric['change'];
                $changeColor = $change > 0 ? 'text-emerald-600 dark:text-emerald-400' : ($change < 0 ? 'text-rose-600 dark:text-rose-400' : 'text-zinc-500 dark:text-zinc-400');
            @endphp

{{ $metric['label'] }}

{{ $metric['value'] }}

                        <flux:icon :name="$metric['icon']" class="size-5" />

                    <flux:icon :name="$change >= 0 ? 'arrow-trending-up' : 'arrow-trending-down'" class="size-4" />
                    {{ $change > 0 ? '+' : '' }}{{ number_format($change, 1) }}%

        @endforeach

                    <flux:heading size="lg">Orders over time</flux:heading>
                    <flux:text class="mt-1">Daily order count</flux:text>

                @foreach ($ordersChartData as $point)
                    @php
                        $height = $point['count'] === 0 ? 2 : max(8, (int) round(($point['count'] / $maxOrdersChartCount) * 100));
                    @endphp

                        @if ($loop->first || $loop->last || $loop->iteration % 7 === 0)

{{ $point['label'] }}

                        @endif

                @endforeach

            <flux:heading size="lg">Top products</flux:heading>
            <flux:text class="mt-1">Ranked by order-line revenue</flux:text>

                @forelse ($topProducts as $product)

{{ $product['title'] }}

{{ number_format($product['units_sold']) }} sold

                            {{ \App\Support\Money::format($product['revenue'], $storeCurrency) }}

                @empty

                        <flux:icon name="cube" class="mx-auto size-8 text-zinc-400" />
                        <flux:text class="mt-3">No product sales in this range.</flux:text>

                @endforelse

                <flux:heading size="lg">Conversion funnel</flux:heading>
                <flux:text class="mt-1">Current range activity</flux:text>

        @php
            $maxFunnelValue = max(1, max($funnelData));
            $funnelSteps = [
                'visits' => 'Visits',
                'add_to_cart' => 'Carts',
                'checkout_started' => 'Checkouts',
                'checkout_completed' => 'Orders',
            ];
        @endphp

            @foreach ($funnelSteps as $key => $label)
                @php
                    $value = (int) $funnelData[$key];
                    $width = $value === 0 ? 2 : max(8, (int) round(($value / $maxFunnelValue) * 100));
                @endphp

{{ $label }}

{{ number_format($value) }}

            @endforeach


output:
Chunk ID: f5f2c8
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 2186
Output:
<?php

namespace App\Livewire\Admin;

use App\Enums\FinancialStatus;
use App\Models\Cart;
use App\Models\Checkout;
use App\Models\Order;
use App\Models\OrderLine;
use App\Models\Store;
use App\Support\Money;
use Carbon\CarbonInterface;
use Carbon\CarbonPeriod;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Carbon;
use Livewire\Attributes\Computed;
use Livewire\Attributes\Locked;
use Livewire\Component;
use Throwable;

class Dashboard extends Component
{
    #[Locked]
    public int $storeId;

    public string $storeCurrency = 'EUR';

    public string $dateRange = 'last_30_days';

    public ?string $customStartDate = null;

    public ?string $customEndDate = null;

    public int $totalSales = 0;

    public int $ordersCount = 0;

    public int $averageOrderValue = 0;

    public int $visitorsCount = 0;

    public float $salesChange = 0.0;

    public float $ordersChange = 0.0;

    public float $aovChange = 0.0;

    public float $visitorsChange = 0.0;

    /**
     * @var list<array{date: string, label: string, count: int}>
     */
    public array $ordersChartData = [];

    public int $maxOrdersChartCount = 1;

    /**
     * @var list<array{title: string, units_sold: int, revenue: int}>
     */
    public array $topProducts = [];

    /**
     * @var array{visits: int, add_to_cart: int, checkout_started: int, checkout_completed: int}
     */
    public array $funnelData = [
        'visits' => 0,
        'add_to_cart' => 0,
        'checkout_started' => 0,
        'checkout_completed' => 0,
    ];

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

        abort_unless($store instanceof Store, 404);

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

        $this->loadKpis();
    }

    public function updatedDateRange(): void
    {
        $this->loadKpis();
    }

    public function updatedCustomStartDate(): void
    {
        if ($this->dateRange === 'custom') {
            $this->loadKpis();
        }
    }

    public function updatedCustomEndDate(): void
    {
        if ($this->dateRange === 'custom') {
            $this->loadKpis();
        }
    }

    public function loadKpis(): void
    {
        [$start, $end] = $this->currentRange();
        [$previousStart, $previousEnd] = $this->previousRange($start, $end);

        $this->ordersCount = $this->ordersBetween($start, $end)->count();
        $previousOrdersCount = $this->ordersBetween($previousStart, $previousEnd)->count();

        $this->totalSales = (int) $this->revenueOrdersBetween($start, $end)->sum('total_amount');
        $previousTotalSales = (int) $this->revenueOrdersBetween($previousStart, $previousEnd)->sum('total_amount');

        $revenueOrdersCount = $this->revenueOrdersBetween($start, $end)->count();
        $previousRevenueOrdersCount = $this->revenueOrdersBetween($previousStart, $previousEnd)->count();

        $this->averageOrderValue = $revenueOrdersCount > 0 ? intdiv($this->totalSales, $revenueOrdersCount) : 0;
        $previousAverageOrderValue = $previousRevenueOrdersCount > 0 ? intdiv($previousTotalSales, $previousRevenueOrdersCount) : 0;

        $this->visitorsCount = 0;
        $this->salesChange = $this->percentChange($this->totalSales, $previousTotalSales);
        $this->ordersChange = $this->percentChange($this->ordersCount, $previousOrdersCount);
        $this->aovChange = $this->percentChange($this->averageOrderValue, $previousAverageOrderValue);
        $this->visitorsChange = 0.0;

        $this->loadChart();
        $this->loadTopProducts();
        $this->loadFunnel();
    }

    public function loadChart(): void
    {
        [$start, $end] = $this->currentRange();

        $counts = $this->ordersBetween($start, $end)
            ->selectRaw('date(placed_at) as order_date, count(*) as aggregate')
            ->groupBy('order_date')
            ->pluck('aggregate', 'order_date');

        $this->ordersChartData = collect(CarbonPeriod::create($start->copy()->startOfDay(), '1 day', $end->copy()->startOfDay()))
            ->map(fn (CarbonInterface $date): array => [
                'date' => $date->toDateString(),
                'label' => $date->format('M j'),
                'count' => (int) ($counts[$date->toDateString()] ?? 0),
            ])
            ->values()
            ->all();

        $this->maxOrdersChartCount = max(1, max(array_column($this->ordersChartData, 'count') ?: [0]));
    }

    public function loadTopProducts(): void
    {
        [$start, $end] = $this->currentRange();

        $this->topProducts = OrderLine::query()
            ->selectRaw('order_lines.title_snapshot as title, sum(order_lines.quantity) as units_sold, sum(order_lines.total_amount) as revenue')
            ->join('orders', 'orders.id', '=', 'order_lines.order_id')
            ->where('orders.store_id', $this->storeId)
            ->whereBetween('orders.placed_at', [$start, $end])
            ->whereIn('orders.financial_status', $this->revenueStatuses())
            ->groupBy('order_lines.product_id', 'order_lines.title_snapshot')
            ->orderByDesc('revenue')
            ->limit(5)
            ->get()
            ->map(fn (OrderLine $line): array => [
                'title' => (string) $line->title,
                'units_sold' => (int) $line->units_sold,
                'revenue' => (int) $line->revenue,
            ])
            ->all();
    }

    public function loadFunnel(): void
    {
        [$start, $end] = $this->currentRange();

        $this->funnelData = [
            'visits' => 0,
            'add_to_cart' => Cart::withoutGlobalScopes()
                ->where('store_id', $this->storeId)
                ->whereBetween('created_at', [$start, $end])
                ->count(),
            'checkout_started' => Checkout::withoutGlobalScopes()
                ->where('store_id', $this->storeId)
                ->whereBetween('created_at', [$start, $end])
                ->count(),
            'checkout_completed' => $this->ordersCount,
        ];
    }

    #[Computed]
    public function formattedTotalSales(): string
    {
        return Money::format($this->totalSales, $this->storeCurrency);
    }

    #[Computed]
    public function formattedAov(): string
    {
        return Money::format($this->averageOrderValue, $this->storeCurrency);
    }

    public function render(): mixed
    {
        return view('livewire.admin.dashboard')->layout('layouts.app', [
            'title' => __('Dashboard'),
        ]);
    }

    /**
     * @return array{0: CarbonInterface, 1: CarbonInterface}
     */
    private function currentRange(): array
    {
        return match ($this->dateRange) {
            'today' => [now()->startOfDay(), now()->endOfDay()],
            'last_7_days' => [now()->subDays(6)->startOfDay(), now()->endOfDay()],
            'custom' => $this->customRange() ?? [now()->subDays(29)->startOfDay(), now()->endOfDay()],
            default => [now()->subDays(29)->startOfDay(), now()->endOfDay()],
        };
    }

    /**
     * @return array{0: CarbonInterface, 1: CarbonInterface}
     */
    private function previousRange(CarbonInterface $start, CarbonInterface $end): array
    {
        $days = max(1, $start->copy()->startOfDay()->diffInDays($end->copy()->startOfDay()) + 1);
        $previousEnd = $start->copy()->subSecond();

        return [$start->copy()->subDays($days)->startOfDay(), $previousEnd];
    }

    /**
     * @return array{0: CarbonInterface, 1: CarbonInterface}|null
     */
    private function customRange(): ?array
    {
        if (! $this->customStartDate || ! $this->customEndDate) {
            return null;
        }

        try {
            $start = Carbon::parse($this->customStartDate)->startOfDay();
            $end = Carbon::parse($this->customEndDate)->endOfDay();
        } catch (Throwable) {
            return null;
        }

        if ($end->lessThan($start)) {
            return [$end->startOfDay(), $start->endOfDay()];
        }

        return [$start, $end];
    }

    /**
     * @return Builder<Order>
     */
    private function ordersBetween(CarbonInterface $start, CarbonInterface $end): Builder
    {
        return Order::withoutGlobalScopes()
            ->where('store_id', $this->storeId)
            ->whereBetween('placed_at', [$start, $end]);
    }

    /**
     * @return Builder<Order>
     */
    private function revenueOrdersBetween(CarbonInterface $start, CarbonInterface $end): Builder
    {
        return $this->ordersBetween($start, $end)
            ->whereIn('financial_status', $this->revenueStatuses());
    }

    /**
     * @return list<string>
     */
    private function revenueStatuses(): array


output:
Chunk ID: c4a436
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 1974
Output:

            <flux:heading size="xl">Dashboard</flux:heading>
            <flux:text class="mt-1">Sales, orders, and product movement for the selected store.</flux:text>

            <flux:select wire:model.live="dateRange" aria-label="Date range">
                <flux:select.option value="today">Today</flux:select.option>
                <flux:select.option value="last_7_days">Last 7 days</flux:select.option>
                <flux:select.option value="last_30_days">Last 30 days</flux:select.option>
                <flux:select.option value="custom">Custom</flux:select.option>
            </flux:select>

            <flux:input type="date" wire:model.live="customStartDate" :disabled="$dateRange !== 'custom'" aria-label="Custom range start" />
            <flux:input type="date" wire:model.live="customEndDate" :disabled="$dateRange !== 'custom'" aria-label="Custom range end" />

        @foreach ([
            ['label' => 'Total sales', 'value' => $this->formattedTotalSales, 'change' => $salesChange, 'icon' => 'banknotes'],
            ['label' => 'Orders', 'value' => number_format($ordersCount), 'change' => $ordersChange, 'icon' => 'shopping-bag'],
            ['label' => 'Average order', 'value' => $this->formattedAov, 'change' => $aovChange, 'icon' => 'receipt-percent'],
            ['label' => 'Visitors', 'value' => number_format($visitorsCount), 'change' => $visitorsChange, 'icon' => 'users'],
        ] as $metric)
            @php
                $change = (float) $metric['change'];
                $changeColor = $change > 0 ? 'text-emerald-600 dark:text-emerald-400' : ($change < 0 ? 'text-rose-600 dark:text-rose-400' : 'text-zinc-500 dark:text-zinc-400');
            @endphp

{{ $metric['label'] }}

{{ $metric['value'] }}

                        <flux:icon :name="$metric['icon']" class="size-5" />

                    <flux:icon :name="$change >= 0 ? 'arrow-trending-up' : 'arrow-trending-down'" class="size-4" />
                    {{ $change > 0 ? '+' : '' }}{{ number_format($change, 1) }}%

        @endforeach

                    <flux:heading size="lg">Orders over time</flux:heading>
                    <flux:text class="mt-1">Daily order count</flux:text>

                @foreach ($ordersChartData as $point)
                    @php
                        $height = $point['count'] === 0 ? 2 : max(8, (int) round(($point['count'] / $maxOrdersChartCount) * 100));
                    @endphp

                        @if ($loop->first || $loop->last || $loop->iteration % 7 === 0)

{{ $point['label'] }}

                        @endif

                @endforeach

            <flux:heading size="lg">Top products</flux:heading>
            <flux:text class="mt-1">Ranked by order-line revenue</flux:text>

                @forelse ($topProducts as $product)

{{ $product['title'] }}

{{ number_format($product['units_sold']) }} sold

                            {{ \App\Support\Money::format($product['revenue'], $storeCurrency) }}

                @empty

                        <flux:icon name="cube" class="mx-auto size-8 text-zinc-400" />
                        <flux:text class="mt-3">No product sales in this range.</flux:text>

                @endforelse

                <flux:heading size="lg">Conversion funnel</flux:heading>
                <flux:text class="mt-1">Current range activity</flux:text>

        @php
            $maxFunnelValue = max(1, max($funnelData));
            $funnelSteps = [
                'visits' => 'Visits',
                'add_to_cart' => 'Carts',
                'checkout_started' => 'Checkouts',
                'checkout_completed' => 'Orders',
            ];
        @endphp

            @foreach ($funnelSteps as $key => $label)
                @php
                    $value = (int) $funnelData[$key];
                    $width = $value === 0 ? 2 : max(8, (int) round(($value / $maxFunnelValue) * 100));
                @endphp

{{ $label }}

{{ number_format($value) }}

            @endforeach


command: rg -n "#1001|#1002|#1004|#1005|Order::withoutGlobalScopes\(\)->count\(\)|firstOrFail\(\)" tests -S

query: #1001|#1002|#1004|#1005|Order::withoutGlobalScopes\(\)->count\(\)|firstOrFail\(\)

path: tests

aggregated_output:
tests/Feature/Analytics/AnalyticsServiceTest.php:20:    return Store::query()->where('handle', 'acme-fashion')->firstOrFail();
tests/Feature/Analytics/AnalyticsServiceTest.php:76:        ->firstOrFail();
tests/Feature/Admin/CustomerManagementTest.php:23:    $store = Store::query()->where('handle', 'acme-fashion')->firstOrFail();
tests/Feature/Admin/CustomerManagementTest.php:31:    return User::query()->where('email', 'admin@acme.test')->firstOrFail();
tests/Feature/Admin/CustomerManagementTest.php:134:        ->firstOrFail();
tests/Browser/Admin/CustomerManagementTest.php:39:    $store = Store::query()->where('handle', 'acme-fashion')->firstOrFail();
tests/Browser/Admin/CustomerManagementTest.php:40:    $user = User::query()->where('email', 'admin@acme.test')->firstOrFail();
tests/Browser/Admin/CustomerManagementTest.php:53:        ->firstOrFail();
tests/Browser/Admin/CustomerManagementTest.php:61:        ->firstOrFail();
tests/Browser/Admin/CustomerManagementTest.php:64:        ->firstOrFail();
tests/Browser/Admin/CustomerManagementTest.php:71:        'order_number' => '#1001',
tests/Browser/Admin/CustomerManagementTest.php:150:        ->assertSee('#1001')
tests/Browser/Admin/CollectionManagementTest.php:29:    return Store::query()->where('handle', 'acme-fashion')->firstOrFail();
tests/Browser/Admin/CollectionManagementTest.php:35:    $user = User::query()->where('email', 'admin@acme.test')->firstOrFail();
tests/Browser/Admin/CollectionManagementTest.php:116:        ->firstOrFail();
tests/Feature/DashboardTest.php:16:    $user = User::query()->where('email', 'admin@acme.test')->firstOrFail();
tests/Feature/Orders/OrderServiceTest.php:64:        ->firstOrFail();
tests/Feature/Orders/OrderServiceTest.php:161:    expect($order->order_number)->toBe('#1001')
tests/Feature/Orders/OrderServiceTest.php:179:    $inventory = InventoryItem::withoutGlobalScopes()->where('variant_id', $variant->getKey())->firstOrFail();
tests/Feature/Orders/OrderServiceTest.php:262:        ->and(Order::withoutGlobalScopes()->count())->toBe(1)
tests/Feature/Orders/OrderServiceTest.php:281:    $inventory = InventoryItem::withoutGlobalScopes()->where('variant_id', $variant->getKey())->firstOrFail();
tests/Feature/Orders/OrderServiceTest.php:298:    $inventory = InventoryItem::withoutGlobalScopes()->where('variant_id', $variant->getKey())->firstOrFail();
tests/Feature/Orders/OrderServiceTest.php:300:    expect(Order::withoutGlobalScopes()->count())->toBe(0)
tests/Feature/Admin/OrderManagementTest.php:33:    $store = Store::query()->where('handle', 'acme-fashion')->firstOrFail();
tests/Feature/Admin/OrderManagementTest.php:41:    return User::query()->where('email', 'admin@acme.test')->firstOrFail();
tests/Feature/Admin/OrderManagementTest.php:54:        ->firstOrFail();
tests/Feature/Admin/OrderManagementTest.php:170:    $inventory = InventoryItem::withoutGlobalScopes()->where('variant_id', $variant->getKey())->firstOrFail();
tests/Feature/Admin/OrderManagementTest.php:202:    $fulfillment = Fulfillment::query()->where('order_id', $order->getKey())->firstOrFail();
tests/Feature/Checkout/PricingServicesTest.php:57:        ->firstOrFail();
tests/Feature/Checkout/PricingServicesTest.php:170:    $line = $checkout->cart->lines()->firstOrFail();
tests/Feature/Checkout/PricingServicesTest.php:198:    $line = $checkout->cart->lines()->firstOrFail();
tests/Feature/Admin/AppsDevelopersTest.php:24:    return Store::query()->where('handle', 'acme-fashion')->firstOrFail();
tests/Browser/Admin/SettingsTest.php:31:    return Store::query()->where('handle', 'acme-fashion')->firstOrFail();
tests/Browser/Admin/SettingsTest.php:37:    $user = User::query()->where('email', 'admin@acme.test')->firstOrFail();
tests/Browser/Admin/SettingsTest.php:128:        ->firstOrFail();
tests/Browser/Admin/SettingsTest.php:133:        ->firstOrFail();
tests/Browser/Admin/SettingsTest.php:155:    $settings = TaxSettings::withoutGlobalScopes()->whereKey($store->getKey())->firstOrFail();
tests/Feature/Api/StorefrontCheckoutApiTest.php:22:    return Store::query()->where('handle', 'acme-fashion')->firstOrFail();
tests/Feature/Api/StorefrontCheckoutApiTest.php:30:        ->firstOrFail();
tests/Feature/Api/StorefrontCheckoutApiTest.php:35:        ->firstOrFail();
tests/Feature/Api/StorefrontCheckoutApiTest.php:138:    $inventory = InventoryItem::withoutGlobalScopes()->where('variant_id', $variant->getKey())->firstOrFail();
tests/Feature/Api/StorefrontCheckoutApiTest.php:181:        ->whereHas('zone', fn ($query) => $query->withoutGlobalScopes()->where('store_id', Store::query()->whereKeyNot($store->getKey())->firstOrFail()->getKey()))
tests/Feature/Api/StorefrontCheckoutApiTest.php:182:        ->firstOrFail();
tests/Feature/Admin/AnalyticsDashboardTest.php:21:    return Store::query()->where('handle', 'acme-fashion')->firstOrFail();
tests/Feature/Orders/BankTransferOrderTest.php:40:    $variant = ProductVariant::withoutGlobalScopes()->where('product_id', $product->getKey())->fi…17805 chars truncated…  ->assertSee('#1001')
tests/Browser/Storefront/CheckoutTest.php:238:        ->assertSee('#1001')
tests/Feature/Api/AdminPageApiTest.php:19:    return Store::query()->where('handle', 'acme-fashion')->firstOrFail();
tests/Feature/Api/AdminPageApiTest.php:24:    return User::query()->where('email', 'admin@acme.test')->firstOrFail();
tests/Feature/Admin/SearchSettingsTest.php:23:    return Store::query()->where('handle', 'acme-fashion')->firstOrFail();
tests/Feature/Admin/SearchSettingsTest.php:28:    return User::query()->where('email', 'admin@acme.test')->firstOrFail();
tests/Feature/Admin/SearchSettingsTest.php:50:    $settings = SearchSettings::withoutGlobalScopes()->where('store_id', $store->getKey())->firstOrFail();
tests/Feature/Storefront/CartCheckoutUiTest.php:32:    $store = Store::query()->where('handle', 'acme-fashion')->firstOrFail();
tests/Feature/Storefront/CartCheckoutUiTest.php:43:        ->firstOrFail();
tests/Feature/Storefront/CartCheckoutUiTest.php:48:        ->firstOrFail();
tests/Feature/Storefront/CartCheckoutUiTest.php:90:    $inventory = InventoryItem::withoutGlobalScopes()->where('variant_id', $variant->getKey())->firstOrFail();
tests/Feature/Storefront/CartCheckoutUiTest.php:134:    $checkout = Checkout::withoutGlobalScopes()->where('cart_id', $cart->getKey())->firstOrFail();
tests/Feature/Storefront/CartCheckoutUiTest.php:146:        ->firstOrFail();
tests/Feature/Storefront/CartCheckoutUiTest.php:174:        ->firstOrFail();
tests/Feature/Storefront/CartCheckoutUiTest.php:196:    $checkout = Checkout::withoutGlobalScopes()->where('cart_id', $cart->getKey())->firstOrFail();
tests/Feature/Storefront/CartCheckoutUiTest.php:197:    $inventory = InventoryItem::withoutGlobalScopes()->where('variant_id', $variant->getKey())->firstOrFail();
tests/Feature/Storefront/OrderViewsTest.php:32:    $store = Store::query()->where('handle', 'acme-fashion')->firstOrFail();
tests/Feature/Storefront/OrderViewsTest.php:43:        ->firstOrFail();
tests/Feature/Storefront/OrderViewsTest.php:48:        ->firstOrFail();
tests/Feature/Storefront/OrderViewsTest.php:56:        ->firstOrFail();
tests/Feature/Storefront/OrderViewsTest.php:82:    $order = Order::withoutGlobalScopes()->firstOrFail();
tests/Feature/Storefront/OrderViewsTest.php:118:    $checkout = Checkout::withoutGlobalScopes()->where('cart_id', $cart->getKey())->firstOrFail();
tests/Feature/Storefront/OrderViewsTest.php:119:    $inventory = InventoryItem::withoutGlobalScopes()->where('variant_id', $variant->getKey())->firstOrFail();
tests/Feature/Storefront/OrderViewsTest.php:121:    expect(Order::withoutGlobalScopes()->count())->toBe(0)
tests/Feature/Storefront/OrderViewsTest.php:128:    $customer = Customer::withoutGlobalScopes()->where('store_id', $store->getKey())->firstOrFail();
tests/Feature/Storefront/OrderViewsTest.php:159:    $customer = Customer::withoutGlobalScopes()->where('store_id', $store->getKey())->firstOrFail();
tests/Browser/Storefront/CustomerAccountTest.php:44:    return Store::query()->where('handle', 'acme-fashion')->firstOrFail();
tests/Browser/Storefront/CustomerAccountTest.php:54:        ->firstOrFail();
tests/Browser/Storefront/CustomerAccountTest.php:65:    return collect(['#1001', '#1002', '#1004'])
tests/Browser/Storefront/CustomerAccountTest.php:165:        ->assertSee('#1001')
tests/Browser/Storefront/CustomerAccountTest.php:166:        ->assertSee('#1002')
tests/Browser/Storefront/CustomerAccountTest.php:167:        ->assertSee('#1004')
tests/Browser/Storefront/CustomerAccountTest.php:181:        ->assertSee('#1001')
tests/Feature/Storefront/CustomerAccountTest.php:22:    $store = Store::query()->where('handle', 'acme-fashion')->firstOrFail();
tests/Feature/Storefront/CustomerAccountTest.php:36:        ->firstOrFail();
tests/Feature/Storefront/CustomerAccountTest.php:58:    $orders = collect(['#1001', '#1002', '#1004'])->map(fn (string $orderNumber): Order => Order::factory()
tests/Feature/Storefront/CustomerAccountTest.php:76:        ->assertSee('#1001')
tests/Feature/Storefront/CustomerAccountTest.php:77:        ->assertSee('#1002')
tests/Feature/Storefront/CustomerAccountTest.php:78:        ->assertSee('#1004');
tests/Feature/Storefront/CustomerAccountTest.php:83:        ->assertSee('#1001')
tests/Feature/Storefront/CustomerAccountTest.php:112:        ->firstOrFail();
tests/Feature/Storefront/CustomerAccountTest.php:131:        ->firstOrFail();
tests/Feature/Storefront/ThemeDataTest.php:84:    $store = Store::query()->where('handle', 'acme-fashion')->firstOrFail();
tests/Feature/Storefront/ThemeDataTest.php:95:    $store = Store::query()->where('handle', 'acme-fashion')->firstOrFail();
tests/Feature/Storefront/ThemeDataTest.php:99:        ->firstOrFail();
tests/Feature/Storefront/ThemeDataTest.php:116:    $store = Store::query()->where('handle', 'acme-fashion')->firstOrFail();
tests/Feature/Cart/CartServiceTest.php:34:        ->firstOrFail();
tests/Feature/Cart/CartServiceTest.php:98:        ->firstOrFail();