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

aggregated_output:
<?php

namespace App\Livewire\Admin\Pages;

use App\Actions\SanitizeHtml;
use App\Enums\PageStatus;
use App\Models\NavigationMenu;
use App\Models\Page;
use App\Models\Store;
use App\Services\NavigationService;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;
use Livewire\Component;

class Form extends Component
{
    use AuthorizesRequests;

    public ?Page $page = null;

    public string $title = '';

    public string $handle = '';

    public string $bodyHtml = '';

    public string $status = 'draft';

    public string $publishedAt = '';

    public string $actionMessage = '';

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

        abort_unless($store instanceof Store, 404);

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

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

            $this->page = $page;
            $this->fillFromPage($page);

            return;
        }

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

    public function updatedTitle(string $title): void
    {
        if ($this->page instanceof Page || $this->handle !== '') {
            return;
        }

        $this->handle = Str::slug($title);
    }

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

        abort_unless($store instanceof Store, 404);

        $this->authorizeSave();

        $this->handle = Str::slug($this->handle);

        $this->validate([
            'title' => ['required', 'string', 'max:255'],
            'handle' => [
                'required',
                'string',
                'max:255',
                'alpha_dash',
                Rule::unique('pages', 'handle')
                    ->where('store_id', $store->getKey())
                    ->ignore($this->page?->getKey()),
            ],
            'bodyHtml' => ['nullable', 'string'],
            'status' => ['required', Rule::in(array_column(PageStatus::cases(), 'value'))],
            'publishedAt' => ['nullable', 'date'],
        ], [], [
            'bodyHtml' => 'body',
            'publishedAt' => 'published at',
        ]);

        $publishedAt = $this->publishedAt !== '' ? $this->publishedAt : null;

        if ($this->status === PageStatus::Published->value && $publishedAt === null) {
            $publishedAt = now();
        }

        $page = $this->page instanceof Page
            ? tap($this->page)->update($this->payload($store, $publishedAt))
            : Page::withoutGlobalScopes()->create($this->payload($store, $publishedAt));

        $this->page = $page->refresh();
        $this->fillFromPage($this->page);
        $this->forgetNavigation($store, $navigation);

        $this->actionMessage = 'Page saved';

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

    public function deletePage(NavigationService $navigation): void
    {
        abort_unless($this->page instanceof Page, 404);

        $store = app('current_store');

        abort_unless($store instanceof Store, 404);

        $this->authorize('delete', $this->page);

        $this->page->delete();
        $this->forgetNavigation($store, $navigation);

        $this->redirectRoute('admin.pages.index', navigate: true);
    }

    public function render(): mixed
    {
        return view('livewire.admin.pages.form', [
            'isEditing' => $this->page instanceof Page,
        ])->layout('layouts.app', [
            'title' => $this->page ? __('Edit page') : __('Create page'),
        ]);
    }

    private function fillFromPage(Page $page): void
    {
        $this->title = $page->title;
        $this->handle = $page->handle;
        $this->bodyHtml = (string) $page->body_html;
        $this->status = $page->status->value;
        $this->publishedAt = $page->published_at?->format('Y-m-d\TH:i') ?? '';
    }

    /**
     * @return array<string, mixed>
     */
    private function payload(Store $store, mixed $publishedAt): array
    {
        return [
            'store_id' => $store->getKey(),
            'title' => $this->title,
            'handle' => $this->handle,
            'body_html' => $this->sanitizeHtml($this->bodyHtml),
            'status' => PageStatus::from($this->status),
            'published_at' => $publishedAt,
        ];
    }

    private function sanitizeHtml(?string $html): ?string
    {
        $sanitized = app(SanitizeHtml::class)($html);

        return $sanitized === '' ? null : $sanitized;
    }

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

            return;
        }

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

    private function forgetNavigation(Store $store, NavigationService $navigation): void
    {
        NavigationMenu::withoutGlobalScopes()
            ->where('store_id', $store->getKey())
            ->get()
            ->each(fn (NavigationMenu $menu): mixed => $navigation->forget($menu));
    }
}


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

namespace App\Http\Controllers\Api\Admin\V1;

use App\Actions\SanitizeHtml;
use App\Enums\MediaStatus;
use App\Enums\MediaType;
use App\Enums\ProductStatus;
use App\Enums\VariantStatus;
use App\Exceptions\InvalidProductTransitionException;
use App\Http\Controllers\Controller;
use App\Http\Requests\Api\Admin\V1\CreateProductMediaUploadRequest;
use App\Http\Requests\Api\Admin\V1\StoreProductRequest;
use App\Http\Requests\Api\Admin\V1\UpdateProductRequest;
use App\Http\Resources\Admin\V1\ProductResource;
use App\Models\InventoryItem;
use App\Models\Product;
use App\Models\ProductMedia;
use App\Models\ProductOption;
use App\Models\ProductOptionValue;
use App\Models\ProductVariant;
use App\Models\Store;
use App\Services\ProductService;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Filesystem\FilesystemAdapter;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;
use Illuminate\Validation\ValidationException;
use InvalidArgumentException;
use RuntimeException;
use Throwable;

class ProductController extends Controller
{
    public function index(Request $request, Store $store): AnonymousResourceCollection
    {
        $this->authorizeStore($request, $store);

        $validated = $request->validate([
            'status' => ['nullable', Rule::in(['draft', 'active', 'archived'])],
            'query' => ['nullable', 'string', 'max:255'],
            'collection_id' => ['nullable', 'integer'],
            'sort' => ['nullable', Rule::in(['title_asc', 'title_desc', 'created_at_asc', 'created_at_desc', 'updated_at_desc'])],
            'per_page' => ['nullable', 'integer', 'min:1', 'max:100'],
        ]);

        $query = Product::withoutGlobalScopes()
            ->with([
                'media',
                'variants.inventoryItem',
            ])
            ->withCount('variants')
            ->where('store_id', $store->getKey())
            ->when(data_get($validated, 'status'), fn (Builder $query, string $status) => $query->where('status', $status))
            ->when(data_get($validated, 'collection_id'), function (Builder $query, int $collectionId): void {
                $query->whereHas('collections', fn (Builder $query) => $query->withoutGlobalScopes()->whereKey($collectionId));
            })
            ->when(data_get($validated, 'query'), function (Builder $query, string $search): void {
                $like = '%'.$search.'%';

                $query->where(function (Builder $query) use ($like): void {
                    $query
                        ->where('title', 'like', $like)
                        ->orWhere('vendor', 'like', $like)
                        ->orWhereHas('variants', fn (Builder $query) => $query->withoutGlobalScopes()->where('sku', 'like', $like));
                });
            });

        $this->applySort($query, (string) data_get($validated, 'sort', 'updated_at_desc'));

        return ProductResource::collection($query->paginate((int) data_get($validated, 'per_page', 25)));
    }

    public function show(Request $request, Store $store, Product $product): ProductResource
    {
        $this->authorizeStore($request, $store);
        $this->abortUnlessProductBelongsToStore($product, $store);

        return ProductResource::make($this->loadProduct($product));
    }

    public function store(StoreProductRequest $request, Store $store, ProductService $products): JsonResponse
    {
        $this->authorizeStore($request, $store);

        $validated = $request->validated();

        try {
            $product = DB::transaction(function () use ($products, $store, $validated): Product {
                $product = $products->create($store, $this->attributesForCreate($validated, $store));

                if (array_key_exists('collections', $validated)) {
                    $product->collections()->sync($this->integerList($validated['collections']));
                }

                return $product->refresh();
            });
        } catch (InvalidProductTransitionException|InvalidArgumentException|RuntimeException $exception) {
            $this->throwProductValidationException($exception);
        }

        return ProductResource::make($this->loadProduct($product))
            ->response()
            ->setStatusCode(201);
    }

    public function update(UpdateProductRequest $request, Store $store, Product $product, ProductService $products): ProductResource
    {
        $this->authorizeStore($request, $store);
        $this->abortUnlessProductBelongsToStore($product, $store);

        $validated = $request->validated();

        try {
            $product = DB::transaction(function () use ($products, $store, $product, $validated): Product {
                $product = Product::withoutGlobalScopes()
                    ->whereKey($product->getKey())
                    ->lockForUpdate()
                    ->firstOrFail();

                $attributes = $this->attributesForUpdate($validated);
                $requestedStatus = null;

                if (array_key_exists('status', $attributes)) {
                    $requestedStatus = ProductStatus::from((string) $attributes['status']);
                    unset($attributes['status']);
                }

                if ($attributes !== []) {
                    $product = $products->update($product, $attributes);
                }

                if (array_key_exists('options', $validated)) {
                    $this->replaceProductOptions($product, $this->optionPayload($validated));
                }

                if (array_key_exists('variants', $validated)) {
                    $this->syncProductVariants($product, $store, $validated['variants']);
                }

                if (array_key_exists('collections', $validated)) {
                    $product->collections()->sync($this->integerList($validated['collections']));
                }

                if ($requestedStatus instanceof ProductStatus && $requestedStatus !== $product->refresh()->status) {
                    $products->transitionStatus($product, $requestedStatus);
                }

                return $product->refresh();
            });
        } catch (InvalidProductTransitionException|InvalidArgumentException|RuntimeException $exception) {
            $this->throwProductValidationException($exception);
        }

        return ProductResource::make($this->loadProduct($product));
    }

    public function destroy(Request $request, Store $store, Product $product, ProductService $products): JsonResponse
    {
        $this->authorizeStore($request, $store);
        $this->abortUnlessProductBelongsToStore($product, $store);

        $products->transitionStatus($product, ProductStatus::Archived);

        return response()->json([
            'data' => [
                'id' => $product->getKey(),
                'status' => ProductStatus::Archived->value,
                'updated_at' => $product->refresh()->updated_at?->toIso8601String(),
            ],
        ]);
    }

    public function presignUpload(CreateProductMediaUploadRequest $request, Store $store, Product $product): JsonResponse
    {
        $this->authorizeStore($request, $store);
        $this->abortUnlessProductBelongsToStore($product, $store);

        $validated = $request->validated();
        $expiresAt = now()->addMinutes(10);
        $storageKey = sprintf(
            'media/originals/%d/%s.%s',
            $product->getKey(),
            Str::uuid(),
            $this->extensionForContentType((string) $validated['content_type']),
        );
        $media = ProductMedia::withoutGlobalScopes()->create([
            'product_id' => $product->getKey(),
            'type' => $this->mediaTypeForContentType((string) $validated['content_type']),
            'storage_key' => $storageKey,
            'alt_text' => $product->title,
            'mime_type' => $validated['content_type'],
            'byte_size' => (int) $validated['byte_size'],
            'position' => $this->nextMediaPosition($product),
            'status' => MediaStatus::Processing,
        ]);
        $upload = $this->temporaryUploadPayload(Storage::disk('public'), $storageKey, $expiresAt);

        return response()->json([
            'upload_url' => $upload['url'],
            'method' => 'PUT',
            'headers' => [
                ...$upload['headers'],
                'Content-Type' => $validated['content_type'],
            ],
            'storage_key' => $storageKey,
            'media_id' => $media->getKey(),
            'expires_at' => $expiresAt->toIso8601String(),
        ], 201);
    }

    private function authorizeStore(Request $request, Store $store): void
    {
        if (! $request->attributes->has('admin_api_oauth_token')) {
            abort_unless($request->user()?->stores()->whereKey($store->getKey())->exists(), 403);
        }

        app()->instance('current_store', $store);
    }

    private function abortUnlessProductBelongsToStore(Product $product, Store $store): void
    {
        abort_unless((int) $product->store_id === $store->getKey(), 404);
    }

    private function loadProduct(Product $product): Product
    {
        return $product->load([
            'collections',
            'media',
            'options.values',
            'variants.inventoryItem',
            'variants.optionValues.option',
        ])->loadCount('variants');
    }

    private function applySort(Builder $query, string $sort): void
    {
        match ($sort) {
            'title_asc' => $query->orderBy('title')->orderBy('id'),
            'title_desc' => $query->orderByDesc('title')->orderByDesc('id'),
            'created_at_asc' => $query->orderBy('created_at')->orderBy('id'),
            'created_at_desc' => $query->orderByDesc('created_at')->orderByDesc('id'),
            default => $query->orderByDesc('updated_at')->orderByDesc('id'),
        };
    }

    /**
     * @param  array<string, mixed>  $validated
     * @return array<string, mixed>
     */
    private function attributesForCreate(array $validated, Store $store): array
    {
        $attributes = [
            'title' => $validated['title'],
            'description_html' => $this->sanitizeHtml($validated['description_html'] ?? null),
            'vendor' => $validated['vendor'] ?? null,
            'product_type' => $validated['product_type'] ?? null,
            'status' => $validated['status'] ?? ProductStatus::Draft->value,
            'tags' => $this->tagList($validated['tags'] ?? []),
            'options' => $this->optionPayload($validated),
            'variants' => $this->variantPayloads($validated['variants'], $store, true),
        ];

        if (filled($validated['handle'] ?? null)) {
            $attributes['handle'] = Str::slug((string) $validated['handle']);
        }

        return $attributes;
    }

    /**
     * @param  array<string, mixed>  $validated
     * @return array<string, mixed>
     */
    private function attributesForUpdate(array $validated): array
    {
        $attributes = Arr::only($validated, [
            'title',
            'description_html',
            'vendor',
            'product_type',
            'status',
        ]);

        if (array_key_exists('tags', $validated)) {
            $attributes['tags'] = $this->tagList($validated['tags']);
        }

        if (array_key_exists('description_html', $attributes)) {
            $attributes['description_html'] = $this->sanitizeHtml($attributes['description_html']);
        }


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

namespace App\Http\Controllers\Api\Admin\V1;

use App\Exceptions\InvalidRefundOperationException;
use App\Http\Controllers\Controller;
use App\Http\Requests\Api\Admin\V1\CreateOrderRefundRequest;
use App\Http\Resources\Admin\V1\RefundResource;
use App\Models\Order;
use App\Models\Store;
use App\Services\RefundService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class OrderRefundController extends Controller
{
    public function store(CreateOrderRefundRequest $request, Store $store, Order $order, RefundService $refunds): RefundResource|JsonResponse
    {
        $this->authorizeStore($request, $store);
        $this->abortUnlessOrderBelongsToStore($order, $store);

        $payload = [
            'lines' => $request->lineQuantities(),
            'reason' => $request->validated('reason'),
            'restock' => (bool) $request->validated('restock', false),
        ];

        if ($request->validated('amount') !== null) {
            $payload['amount'] = $request->validated('amount');
        }

        try {
            $refund = $refunds->process($order, $payload);

            return RefundResource::make($refund)
                ->response()
                ->setStatusCode(201);
        } catch (InvalidRefundOperationException $exception) {
            return response()->json(['message' => $exception->getMessage()], 409);
        }
    }

    private function authorizeStore(Request $request, Store $store): void
    {
        if (! $request->attributes->has('admin_api_oauth_token')) {
            abort_unless($request->user()?->stores()->whereKey($store->getKey())->exists(), 403);
        }

        app()->instance('current_store', $store);
    }

    private function abortUnlessOrderBelongsToStore(Order $order, Store $store): void
    {
        abort_unless((int) $order->store_id === $store->getKey(), 404);
    }
}


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

namespace App\Http\Controllers\Api\Admin\V1;

use App\Exceptions\InvalidFulfillmentOperationException;
use App\Http\Controllers\Controller;
use App\Http\Requests\Api\Admin\V1\CreateOrderFulfillmentRequest;
use App\Http\Resources\Admin\V1\FulfillmentResource;
use App\Models\Order;
use App\Models\Store;
use App\Services\FulfillmentService;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;

class OrderFulfillmentController extends Controller
{
    public function store(CreateOrderFulfillmentRequest $request, Store $store, Order $order, FulfillmentService $fulfillments): FulfillmentResource|JsonResponse
    {
        $this->authorizeStore($request, $store);
        $this->abortUnlessOrderBelongsToStore($order, $store);

        try {
            $fulfillment = $fulfillments->create($order, $request->lineQuantities(), [
                'tracking_company' => $request->validated('tracking_company'),
                'tracking_number' => $request->validated('tracking_number'),
                'tracking_url' => $request->validated('tracking_url'),
            ]);

            return FulfillmentResource::make($fulfillment->load('lines'))
                ->response()
                ->setStatusCode(201);
        } catch (InvalidFulfillmentOperationException $exception) {
            return response()->json(['message' => $exception->getMessage()], 409);
        }
    }

    private function authorizeStore(Request $request, Store $store): void
    {
        if (! $request->attributes->has('admin_api_oauth_token')) {
            abort_unless($request->user()?->stores()->whereKey($store->getKey())->exists(), 403);
        }

        app()->instance('current_store', $store);
    }

    private function abortUnlessOrderBelongsToStore(Order $order, Store $store): void
    {
        abort_unless((int) $order->store_id === $store->getKey(), 404);
    }
}


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

namespace App\Http\Controllers\Api\Admin\V1;

use App\Http\Controllers\Controller;
use App\Http\Resources\Admin\V1\CollectionResource;
use App\Models\Collection;
use App\Models\Store;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Http\JsonResponse;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
use Illuminate\Support\Arr;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;

class CollectionController extends Controller
{
    public function index(Request $request, Store $store): AnonymousResourceCollection
    {
        $this->authorizeStore($request, $store);

        $validated = $request->validate([
            'status' => ['nullable', Rule::in(['draft', 'active', 'archived'])],
            'query' => ['nullable', 'string', 'max:255'],
            'per_page' => ['nullable', 'integer', 'min:1', 'max:100'],
        ]);

        $collections = Collection::withoutGlobalScopes()
            ->withCount('products')
            ->where('store_id', $store->getKey())
            ->when(data_get($validated, 'status'), fn (Builder $query, string $status) => $query->where('status', $status))
            ->when(data_get($validated, 'query'), function (Builder $query, string $search): void {
                $query->where('title', 'like', '%'.$search.'%');
            })
            ->latest('updated_at')
            ->latest('id')
            ->paginate((int) data_get($validated, 'per_page', 25));

        return CollectionResource::collection($collections);
    }

    public function store(Request $request, Store $store): JsonResponse
    {
        $this->authorizeStore($request, $store);

        $validated = $this->validatePayload($request, $store);

        $collection = DB::transaction(function () use ($store, $validated): Collection {
            $collection = Collection::withoutGlobalScopes()->create([
                'store_id' => $store->getKey(),
                ...$this->attributesForCreate($validated),
            ]);

            if (array_key_exists('product_ids', $validated)) {
                $this->replaceProducts($collection, $validated['product_ids']);
            }

            return $collection;
        });

        return CollectionResource::make($this->loadCollection($collection))
            ->response()
            ->setStatusCode(201);
    }

    public function update(Request $request, Store $store, Collection $collection): CollectionResource
    {
        $this->authorizeStore($request, $store);
        $this->abortUnlessCollectionBelongsToStore($collection, $store);

        $validated = $this->validatePayload($request, $store, $collection);

        DB::transaction(function () use ($collection, $validated): void {
            $attributes = $this->attributesForUpdate($validated);

            if ($attributes !== []) {
                $collection->update($attributes);
            }

            if (array_key_exists('product_ids', $validated)) {
                $this->replaceProducts($collection, $validated['product_ids']);
            } else {
                $this->addProducts($collection, $validated['add_product_ids'] ?? []);
                $this->removeProducts($collection, $validated['remove_product_ids'] ?? []);
            }
        });

        return CollectionResource::make($this->loadCollection($collection->refresh()));
    }

    public function destroy(Request $request, Store $store, Collection $collection): JsonResponse
    {
        $this->authorizeStore($request, $store);
        $this->abortUnlessCollectionBelongsToStore($collection, $store);

        $collection->delete();

        return response()->json(['message' => 'Collection deleted']);
    }

    private function authorizeStore(Request $request, Store $store): void
    {
        if (! $request->attributes->has('admin_api_oauth_token')) {
            abort_unless($request->user()?->stores()->whereKey($store->getKey())->exists(), 403);
        }

        app()->instance('current_store', $store);
    }

    private function abortUnlessCollectionBelongsToStore(Collection $collection, Store $store): void
    {
        abort_unless((int) $collection->store_id === $store->getKey(), 404);
    }

    /**
     * @return array<string, mixed>
     */
    private function validatePayload(Request $request, Store $store, ?Collection $collection = null): array
    {
        $creating = $collection === null;

        return $request->validate([
            'title' => [$creating ? 'required' : 'sometimes', 'string', 'max:255'],
            'handle' => [
                'sometimes',
                'nullable',
                'string',
                'max:255',
                Rule::unique('collections', 'handle')
                    ->where('store_id', $store->getKey())
                    ->ignore($collection?->getKey()),
            ],
            'description_html' => ['sometimes', 'nullable', 'string', 'max:65535'],
            'type' => [$creating ? 'required' : 'sometimes', Rule::in(['manual', 'automated'])],
            'status' => ['sometimes', Rule::in(['draft', 'active', 'archived'])],
            'product_ids' => ['sometimes', 'array'],
            'product_ids.*' => ['integer', Rule::exists('products', 'id')->where('store_id', $store->getKey())],
            'add_product_ids' => ['sometimes', 'array'],
            'add_product_ids.*' => ['integer', Rule::exists('products', 'id')->where('store_id', $store->getKey())],
            'remove_product_ids' => ['sometimes', 'array'],
            'remove_product_ids.*' => ['integer', Rule::exists('products', 'id')->where('store_id', $store->getKey())],
        ]);
    }

    /**
     * @param  array<string, mixed>  $validated
     * @return array<string, mixed>
     */
    private function attributesForCreate(array $validated): array
    {
        $title = (string) $validated['title'];
        $handle = filled($validated['handle'] ?? null) ? (string) $validated['handle'] : $title;

        return [
            'title' => $title,
            'handle' => Str::slug($handle),
            'description_html' => $validated['description_html'] ?? null,
            'type' => $validated['type'],


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

namespace App\Livewire\Admin\Pages;

use App\Actions\SanitizeHtml;
use App\Enums\PageStatus;
use App\Models\NavigationMenu;
use App\Models\Page;
use App\Models\Store;
use App\Services\NavigationService;
use Illuminate\Foundation\Auth\Access\AuthorizesRequests;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;
use Livewire\Component;

class Form extends Component
{
    use AuthorizesRequests;

    public ?Page $page = null;

    public string $title = '';

    public string $handle = '';

    public string $bodyHtml = '';

    public string $status = 'draft';

    public string $publishedAt = '';

    public string $actionMessage = '';

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

        abort_unless($store instanceof Store, 404);

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

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

            $this->page = $page;
            $this->fillFromPage($page);

            return;
        }

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

    public function updatedTitle(string $title): void
    {
        if ($this->page instanceof Page || $this->handle !== '') {
            return;
        }

        $this->handle = Str::slug($title);
    }

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

        abort_unless($store instanceof Store, 404);

        $this->authorizeSave();

        $this->handle = Str::slug($this->handle);

        $this->validate([
            'title' => ['required', 'string', 'max:255'],
            'handle' => [
                'required',
                'string',
                'max:255',
                'alpha_dash',
                Rule::unique('pages', 'handle')
                    ->where('store_id', $store->getKey())
                    ->ignore($this->page?->getKey()),
            ],
            'bodyHtml' => ['nullable', 'string'],
            'status' => ['required', Rule::in(array_column(PageStatus::cases(), 'value'))],
            'publishedAt' => ['nullable', 'date'],
        ], [], [
            'bodyHtml' => 'body',
            'publishedAt' => 'published at',
        ]);

        $publishedAt = $this->publishedAt !== '' ? $this->publishedAt : null;

        if ($this->status === PageStatus::Published->value && $publishedAt === null) {
            $publishedAt = now();
        }

        $page = $this->page instanceof Page
            ? tap($this->page)->update($this->payload($store, $publishedAt))
            : Page::withoutGlobalScopes()->create($this->payload($store, $publishedAt));

        $this->page = $page->refresh();
        $this->fillFromPage($this->page);
        $this->forgetNavigation($store, $navigation);

        $this->actionMessage = 'Page saved';

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

    public function deletePage(NavigationService $navigation): void
    {
        abort_unless($this->page instanceof Page, 404);

        $store = app('current_store');

        abort_unless($store instanceof Store, 404);

        $this->authorize('delete', $this->page);

        $this->page->delete();
        $this->forgetNavigation($store, $navigation);

        $this->redirectRoute('admin.pages.index', navigate: true);
    }

    public function render(): mixed
    {
        return view('livewire.admin.pages.form', [
            'isEditing' => $this->page instanceof Page,
        ])->layout('layouts.app', [
            'title' => $this->page ? __('Edit page') : __('Create page'),
        ]);
    }

    private function fillFromPage(Page $page): void
    {
        $this->title = $page->title;
        $this->handle = $page->handle;
        $this->bodyHtml = (string) $page->body_html;
        $this->status = $page->status->value;
        $this->publishedAt = $page->published_at?->format('Y-m-d\TH:i') ?? '';
    }

    /**
     * @return array<string, mixed>
     */
    private function payload(Store $store, mixed $publishedAt): array
    {
        return [
            'store_id' => $store->getKey(),
            'title' => $this->title,
            'handle' => $this->handle,
            'body_html' => $this->sanitizeHtml($this->bodyHtml),
            'status' => PageStatus::from($this->status),
            'published_at' => $publishedAt,
        ];
    }

    private function sanitizeHtml(?string $html): ?string
    {
        $sanitized = app(SanitizeHtml::class)($html);

        return $sanitized === '' ? null : $sanitized;
    }

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

            return;
        }

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

    private function forgetNavigation(Store $store, NavigationService $navigation): void
    {
        NavigationMenu::withoutGlobalScopes()
            ->where('store_id', $store->getKey())
            ->get()
            ->each(fn (NavigationMenu $menu): mixed => $navigation->forget($menu));
    }
}


command: sed -n '1,240p' app/Actions/SanitizeHtml.php

SanitizeHtml.php

type: read

aggregated_output:
<?php

namespace App\Actions;

use DOMDocument;
use DOMElement;
use DOMNode;
use DOMXPath;

class SanitizeHtml
{
    /**
     * @var array<string, list<string>>
     */
    private const array AllowedElements = [
        'p' => [],
        'br' => [],
        'strong' => [],
        'em' => [],
        'u' => [],
        'ol' => [],
        'ul' => [],
        'li' => [],
        'a' => ['href'],
        'img' => ['src', 'alt'],
        'h1' => [],
        'h2' => [],
        'h3' => [],
        'h4' => [],
        'h5' => [],
        'h6' => [],
        'blockquote' => [],
        'table' => [],
        'thead' => [],
        'tbody' => [],
        'tr' => [],
        'th' => [],
        'td' => [],
        'div' => [],
        'span' => [],
    ];

    /**
     * @var list<string>
     */
    private const array DangerousElements = [
        'base',
        'button',
        'canvas',
        'embed',
        'form',
        'iframe',
        'input',
        'link',
        'math',
        'meta',
        'object',
        'script',
        'select',
        'style',
        'svg',
        'textarea',
    ];

    /**
     * @var list<string>
     */
    private const array EmptyAllowedElements = ['br', 'img'];

    public function __invoke(?string $html): ?string
    {
        if ($html === null) {
            return null;
        }

        $html = trim($html);

        if ($html === '') {
            return '';
        }

        $document = new DOMDocument('1.0', 'UTF-8');
        $previous = libxml_use_internal_errors(true);

        try {
            $document->loadHTML($this->wrapHtml($html), LIBXML_NONET | LIBXML_NOERROR | LIBXML_NOWARNING);
            $root = $this->rootElement($document);

            if (! $root instanceof DOMElement) {
                return '';
            }

            $this->sanitizeChildren($root);
            $this->removeEmptyElements($root);

            return trim($this->innerHtml($root));
        } finally {
            libxml_clear_errors();
            libxml_use_internal_errors($previous);
        }
    }

    private function wrapHtml(string $html): string
    {
        return '<!DOCTYPE html><meta charset="utf-8">
'.$html.'
';
    }

    private function rootElement(DOMDocument $document): ?DOMElement
    {
        $root = (new DOMXPath($document))->query('//*[@id="__sanitize_html_root"]')?->item(0);

        return $root instanceof DOMElement ? $root : null;
    }

    private function sanitizeChildren(DOMNode $parent): void
    {
        foreach ($this->childNodes($parent) as $child) {
            if ($child instanceof DOMElement) {
                $this->sanitizeElement($child);

                continue;
            }

            if ($child->nodeType !== XML_TEXT_NODE) {
                $parent->removeChild($child);
            }
        }
    }

    private function sanitizeElement(DOMElement $element): void
    {
        $tagName = strtolower($element->tagName);

        if (in_array($tagName, self::DangerousElements, true)) {
            $element->parentNode?->removeChild($element);

            return;
        }

        if (! array_key_exists($tagName, self::AllowedElements)) {
            $this->sanitizeChildren($element);
            $this->unwrapElement($element);

            return;
        }

        $this->sanitizeAttributes($element, self::AllowedElements[$tagName]);
        $this->sanitizeChildren($element);
    }

    /**
     * @param  list<string>  $allowedAttributes
     */
    private function sanitizeAttributes(DOMElement $element, array $allowedAttributes): void
    {
        foreach ($this->attributeNames($element) as $attributeName) {
            $normalizedName = strtolower($attributeName);

            if (! in_array($normalizedName, $allowedAttributes, true)) {
                $element->removeAttribute($attributeName);

                continue;
            }

            $value = trim($element->getAttribute($attributeName));

            if ($this->isUrlAttribute($normalizedName) && ! $this->isSafeUrl($normalizedName, $value)) {
                $element->removeAttribute($attributeName);

                continue;
            }

            $element->setAttribute($normalizedName, $value);
        }
    }

    private function isUrlAttribute(string $attributeName): bool
    {
        return in_array($attributeName, ['href', 'src'], true);
    }

    private function isSafeUrl(string $attributeName, string $value): bool
    {
        if ($value === '' || preg_match('/[\x00-\x1F\x7F]/', $value) === 1) {
            return false;
        }

        $scheme = parse_url($value, PHP_URL_SCHEME);

        if ($scheme === null) {
            return true;
        }

        $allowedSchemes = $attributeName === 'href'
            ? ['http', 'https', 'mailto', 'tel']
            : ['http', 'https'];

        return in_array(strtolower($scheme), $allowedSchemes, true);
    }

    private function unwrapElement(DOMElement $element): void
    {
        $parent = $element->parentNode;

        if (! $parent instanceof DOMNode) {
            return;
        }

        while ($element->firstChild instanceof DOMNode) {
            $parent->insertBefore($element->firstChild, $element);
        }

        $parent->removeChild($element);
    }

    private function removeEmptyElements(DOMNode $parent): void
    {
        foreach ($this->childNodes($parent) as $child) {
            if (! $child instanceof DOMElement) {
                continue;
            }

            $this->removeEmptyElements($child);

            if ($this->isEmptyElement($child)) {
                $child->parentNode?->removeChild($child);
            }
        }
    }

    private function isEmptyElement(DOMElement $element): bool
    {
        $tagName = strtolower($element->tagName);

        if ($tagName === 'br') {
            return false;
        }

        if ($tagName === 'img') {
            return ! $element->hasAttribute('src');

status: completed


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

namespace App\Actions;

use DOMDocument;
use DOMElement;
use DOMNode;
use DOMXPath;

class SanitizeHtml
{
    /**
     * @var array<string, list<string>>
     */
    private const array AllowedElements = [
        'p' => [],
        'br' => [],
        'strong' => [],
        'em' => [],
        'u' => [],
        'ol' => [],
        'ul' => [],
        'li' => [],
        'a' => ['href'],
        'img' => ['src', 'alt'],
        'h1' => [],
        'h2' => [],
        'h3' => [],
        'h4' => [],
        'h5' => [],
        'h6' => [],
        'blockquote' => [],
        'table' => [],
        'thead' => [],
        'tbody' => [],
        'tr' => [],
        'th' => [],
        'td' => [],
        'div' => [],
        'span' => [],
    ];

    /**
     * @var list<string>
     */
    private const array DangerousElements = [
        'base',
        'button',
        'canvas',
        'embed',
        'form',
        'iframe',
        'input',
        'link',
        'math',
        'meta',
        'object',
        'script',
        'select',
        'style',
        'svg',
        'textarea',
    ];

    /**
     * @var list<string>
     */
    private const array EmptyAllowedElements = ['br', 'img'];

    public function __invoke(?string $html): ?string
    {
        if ($html === null) {
            return null;
        }

        $html = trim($html);

        if ($html === '') {
            return '';
        }

        $document = new DOMDocument('1.0', 'UTF-8');
        $previous = libxml_use_internal_errors(true);

        try {
            $document->loadHTML($this->wrapHtml($html), LIBXML_NONET | LIBXML_NOERROR | LIBXML_NOWARNING);
            $root = $this->rootElement($document);

            if (! $root instanceof DOMElement) {
                return '';
            }

            $this->sanitizeChildren($root);
            $this->removeEmptyElements($root);

            return trim($this->innerHtml($root));
        } finally {
            libxml_clear_errors();
            libxml_use_internal_errors($previous);
        }
    }

    private function wrapHtml(string $html): string
    {
        return '<!DOCTYPE html><meta charset="utf-8">
'.$html.'
';
    }

    private function rootElement(DOMDocument $document): ?DOMElement
    {
        $root = (new DOMXPath($document))->query('//*[@id="__sanitize_html_root"]')?->item(0);

        return $root instanceof DOMElement ? $root : null;
    }

    private function sanitizeChildren(DOMNode $parent): void
    {
        foreach ($this->childNodes($parent) as $child) {
            if ($child instanceof DOMElement) {
                $this->sanitizeElement($child);

                continue;
            }

            if ($child->nodeType !== XML_TEXT_NODE) {
                $parent->removeChild($child);
            }
        }
    }

    private function sanitizeElement(DOMElement $element): void
    {
        $tagName = strtolower($element->tagName);

        if (in_array($tagName, self::DangerousElements, true)) {
            $element->parentNode?->removeChild($element);

            return;
        }

        if (! array_key_exists($tagName, self::AllowedElements)) {
            $this->sanitizeChildren($element);
            $this->unwrapElement($element);

            return;
        }

        $this->sanitizeAttributes($element, self::AllowedElements[$tagName]);
        $this->sanitizeChildren($element);
    }

    /**
     * @param  list<string>  $allowedAttributes
     */
    private function sanitizeAttributes(DOMElement $element, array $allowedAttributes): void
    {
        foreach ($this->attributeNames($element) as $attributeName) {
            $normalizedName = strtolower($attributeName);

            if (! in_array($normalizedName, $allowedAttributes, true)) {
                $element->removeAttribute($attributeName);

                continue;
            }

            $value = trim($element->getAttribute($attributeName));

            if ($this->isUrlAttribute($normalizedName) && ! $this->isSafeUrl($normalizedName, $value)) {
                $element->removeAttribute($attributeName);

                continue;
            }

            $element->setAttribute($normalizedName, $value);
        }
    }

    private function isUrlAttribute(string $attributeName): bool
    {
        return in_array($attributeName, ['href', 'src'], true);
    }

    private function isSafeUrl(string $attributeName, string $value): bool
    {
        if ($value === '' || preg_match('/[\x00-\x1F\x7F]/', $value) === 1) {
            return false;
        }

        $scheme = parse_url($value, PHP_URL_SCHEME);

        if ($scheme === null) {
            return true;
        }

        $allowedSchemes = $attributeName === 'href'
            ? ['http', 'https', 'mailto', 'tel']
            : ['http', 'https'];

        return in_array(strtolower($scheme), $allowedSchemes, true);
    }

    private function unwrapElement(DOMElement $element): void
    {
        $parent = $element->parentNode;

        if (! $parent instanceof DOMNode) {
            return;
        }

        while ($element->firstChild instanceof DOMNode) {
            $parent->insertBefore($element->firstChild, $element);
        }

        $parent->removeChild($element);
    }

    private function removeEmptyElements(DOMNode $parent): void
    {
        foreach ($this->childNodes($parent) as $child) {
            if (! $child instanceof DOMElement) {
                continue;
            }

            $this->removeEmptyElements($child);

            if ($this->isEmptyElement($child)) {
                $child->parentNode?->removeChild($child);
            }
        }
    }

    private function isEmptyElement(DOMElement $element): bool
    {
        $tagName = strtolower($element->tagName);

        if ($tagName === 'br') {
            return false;
        }

        if ($tagName === 'img') {
            return ! $element->hasAttribute('src');


cmd: sed -n '240,420p' app/Actions/SanitizeHtml.php


command: sed -n '240,420p' app/Actions/SanitizeHtml.php

aggregated_output:
            return ! $element->hasAttribute('src');
        }

        foreach ($element->childNodes as $child) {
            if ($child instanceof DOMElement) {
                return false;
            }

            if ($child->nodeType === XML_TEXT_NODE && trim((string) $child->textContent) !== '') {
                return false;
            }
        }

        return true;
    }

    /**
     * @return list<DOMNode>
     */
    private function childNodes(DOMNode $node): array
    {
        return iterator_to_array($node->childNodes);
    }

    /**
     * @return list<string>
     */
    private function attributeNames(DOMElement $element): array
    {
        return collect($element->attributes)
            ->map(fn ($attribute): string => $attribute->nodeName)
            ->all();
    }

    private function innerHtml(DOMElement $element): string
    {
        return collect($element->childNodes)
            ->map(fn (DOMNode $child): string => $element->ownerDocument?->saveHTML($child) ?: '')
            ->implode('');
    }
}


output:
Chunk ID: 347fe3
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 264
Output:
            return ! $element->hasAttribute('src');
        }

        foreach ($element->childNodes as $child) {
            if ($child instanceof DOMElement) {
                return false;
            }

            if ($child->nodeType === XML_TEXT_NODE && trim((string) $child->textContent) !== '') {
                return false;
            }
        }

        return true;
    }

    /**
     * @return list<DOMNode>
     */
    private function childNodes(DOMNode $node): array
    {
        return iterator_to_array($node->childNodes);
    }

    /**
     * @return list<string>
     */
    private function attributeNames(DOMElement $element): array
    {
        return collect($element->attributes)
            ->map(fn ($attribute): string => $attribute->nodeName)
            ->all();
    }

    private function innerHtml(DOMElement $element): string
    {
        return collect($element->childNodes)
            ->map(fn (DOMNode $child): string => $element->ownerDocument?->saveHTML($child) ?: '')
            ->implode('');
    }
}


cmd: sed -n '1,220p' app/Traits/ChecksStoreRole.php


command: sed -n '1,220p' app/Traits/ChecksStoreRole.php

aggregated_output:
<?php

namespace App\Traits;

use App\Enums\StoreUserRole;
use App\Models\Store;
use App\Models\User;

trait ChecksStoreRole
{
    public function getStoreRole(User $user, ?int $storeId = null): ?StoreUserRole
    {
        $storeId ??= $this->currentStoreId();

        if (! $storeId) {
            return null;
        }

        return $user->roleForStoreId($storeId);
    }

    /**
     * @param  array<int, StoreUserRole>  $roles
     */
    public function hasRole(User $user, ?int $storeId, array $roles): bool
    {
        $role = $this->getStoreRole($user, $storeId);

        return $role !== null && in_array($role, $roles, true);
    }

    public function isOwnerOnly(User $user, ?int $storeId = null): bool
    {
        return $this->hasRole($user, $storeId, [StoreUserRole::Owner]);
    }

    public function isOwnerOrAdmin(User $user, ?int $storeId = null): bool
    {
        return $this->hasRole($user, $storeId, [StoreUserRole::Owner, StoreUserRole::Admin]);
    }

    public function isOwnerAdminOrStaff(User $user, ?int $storeId = null): bool
    {
        return $this->hasRole($user, $storeId, [StoreUserRole::Owner, StoreUserRole::Admin, StoreUserRole::Staff]);
    }

    public function isAnyRole(User $user, ?int $storeId = null): bool
    {
        return $this->getStoreRole($user, $storeId) !== null;
    }

    protected function currentStoreId(): ?int
    {
        if (! app()->bound('current_store')) {
            return null;
        }

        $store = app('current_store');

        return $store instanceof Store ? $store->getKey() : null;
    }

    protected function storeIdForModel(object $model): ?int
    {
        if (method_exists($model, 'getAttribute')) {
            $storeId = $model->getAttribute('store_id');

            return is_numeric($storeId) ? (int) $storeId : null;
        }

        if (property_exists($model, 'store_id')) {
            return is_numeric($model->store_id) ? (int) $model->store_id : null;
        }

        return null;
    }
}


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

namespace App\Traits;

use App\Enums\StoreUserRole;
use App\Models\Store;
use App\Models\User;

trait ChecksStoreRole
{
    public function getStoreRole(User $user, ?int $storeId = null): ?StoreUserRole
    {
        $storeId ??= $this->currentStoreId();

        if (! $storeId) {
            return null;
        }

        return $user->roleForStoreId($storeId);
    }

    /**
     * @param  array<int, StoreUserRole>  $roles
     */
    public function hasRole(User $user, ?int $storeId, array $roles): bool
    {
        $role = $this->getStoreRole($user, $storeId);

        return $role !== null && in_array($role, $roles, true);
    }

    public function isOwnerOnly(User $user, ?int $storeId = null): bool
    {
        return $this->hasRole($user, $storeId, [StoreUserRole::Owner]);
    }

    public function isOwnerOrAdmin(User $user, ?int $storeId = null): bool
    {
        return $this->hasRole($user, $storeId, [StoreUserRole::Owner, StoreUserRole::Admin]);
    }

    public function isOwnerAdminOrStaff(User $user, ?int $storeId = null): bool
    {
        return $this->hasRole($user, $storeId, [StoreUserRole::Owner, StoreUserRole::Admin, StoreUserRole::Staff]);
    }

    public function isAnyRole(User $user, ?int $storeId = null): bool
    {
        return $this->getStoreRole($user, $storeId) !== null;
    }

    protected function currentStoreId(): ?int
    {
        if (! app()->bound('current_store')) {
            return null;
        }

        $store = app('current_store');

        return $store instanceof Store ? $store->getKey() : null;
    }

    protected function storeIdForModel(object $model): ?int
    {
        if (method_exists($model, 'getAttribute')) {
            $storeId = $model->getAttribute('store_id');

            return is_numeric($storeId) ? (int) $storeId : null;
        }

        if (property_exists($model, 'store_id')) {
            return is_numeric($model->store_id) ? (int) $model->store_id : null;
        }

        return null;
    }
}


cmd: sed -n '1,260p' app/Http/Controllers/Api/Storefront/V1/CheckoutController.php


cmd: sed -n '1,220p' app/Livewire/Storefront/Cart/Show.php


cmd: sed -n '1,110p' app/Livewire/Storefront/CartDrawer.php


command:
/bin/zsh
-lc
sed -n '1,240p' app/Models/Checkout.php

Checkout.php

cmd: sed -n '1,240p' app/Models/Checkout.php

aggregated_output:
<?php

namespace App\Models;

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

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

    /**
     * @var list<string>
     */
    protected $fillable = [
        'store_id',
        'cart_id',
        'customer_id',
        'status',
        'payment_method',
        'email',
        'shipping_address_json',
        'billing_address_json',
        'shipping_method_id',
        'discount_code',
        'tax_provider_snapshot_json',
        'totals_json',
        'expires_at',
    ];

    /**
     * @var array<string, mixed>
     */
    protected $attributes = [
        'status' => 'started',
    ];

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

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

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

    /**
     * @return BelongsTo<ShippingRate, $this>
     */
    public function shippingRate(): BelongsTo
    {
        return $this->belongsTo(ShippingRate::class, 'shipping_method_id');
    }

    /**
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            'status' => CheckoutStatus::class,
            'shipping_address_json' => 'array',
            'billing_address_json' => 'array',
            'shipping_method_id' => 'integer',
            'tax_provider_snapshot_json' => 'array',
            'totals_json' => 'array',
            'expires_at' => 'datetime',
        ];
    }
}


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

namespace App\Models;

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

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

    /**
     * @var list<string>
     */
    protected $fillable = [
        'store_id',
        'cart_id',
        'customer_id',
        'status',
        'payment_method',
        'email',
        'shipping_address_json',
        'billing_address_json',
        'shipping_method_id',
        'discount_code',
        'tax_provider_snapshot_json',
        'totals_json',
        'expires_at',
    ];

    /**
     * @var array<string, mixed>
     */
    protected $attributes = [
        'status' => 'started',
    ];

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

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

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

    /**
     * @return BelongsTo<ShippingRate, $this>
     */
    public function shippingRate(): BelongsTo
    {
        return $this->belongsTo(ShippingRate::class, 'shipping_method_id');
    }

    /**
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            'status' => CheckoutStatus::class,
            'shipping_address_json' => 'array',
            'billing_address_json' => 'array',
            'shipping_method_id' => 'integer',
            'tax_provider_snapshot_json' => 'array',
            'totals_json' => 'array',
            'expires_at' => 'datetime',
        ];
    }
}


command:
/bin/zsh
-lc
sed -n '1,240p' app/Models/Order.php

Order.php

cmd: sed -n '1,240p' app/Models/Order.php

aggregated_output:
<?php

namespace App\Models;

use App\Enums\FinancialStatus;
use App\Enums\FulfillmentStatus;
use App\Enums\OrderStatus;
use App\Enums\PaymentMethod;
use App\Models\Concerns\BelongsToStore;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

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

    /**
     * @var list<string>
     */
    protected $fillable = [
        'store_id',
        'checkout_id',
        'customer_id',
        'order_number',
        'payment_method',
        'status',
        'financial_status',
        'fulfillment_status',
        'currency',
        'subtotal_amount',
        'discount_amount',
        'shipping_amount',
        'tax_amount',
        'total_amount',
        'email',
        'billing_address_json',
        'shipping_address_json',
        'placed_at',
    ];

    /**
     * @var array<string, mixed>
     */
    protected $attributes = [
        'status' => 'pending',
        'financial_status' => 'pending',
        'fulfillment_status' => 'unfulfilled',
        'currency' => 'USD',
        'subtotal_amount' => 0,
        'discount_amount' => 0,
        'shipping_amount' => 0,
        'tax_amount' => 0,
        'total_amount' => 0,
    ];

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

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

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

    /**
     * @return HasMany<OrderLine, $this>
     */
    public function lines(): HasMany
    {
        return $this->hasMany(OrderLine::class);
    }

    /**
     * @return HasMany<Payment, $this>
     */
    public function payments(): HasMany
    {
        return $this->hasMany(Payment::class);
    }

    /**
     * @return HasMany<Refund, $this>
     */
    public function refunds(): HasMany
    {
        return $this->hasMany(Refund::class);
    }

    /**
     * @return HasMany<Fulfillment, $this>
     */
    public function fulfillments(): HasMany
    {
        return $this->hasMany(Fulfillment::class);
    }

    /**
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            'payment_method' => PaymentMethod::class,
            'status' => OrderStatus::class,
            'financial_status' => FinancialStatus::class,
            'fulfillment_status' => FulfillmentStatus::class,
            'subtotal_amount' => 'integer',
            'discount_amount' => 'integer',
            'shipping_amount' => 'integer',
            'tax_amount' => 'integer',
            'total_amount' => 'integer',
            'billing_address_json' => 'array',
            'shipping_address_json' => 'array',
            'placed_at' => 'datetime',
        ];
    }
}


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

namespace App\Models;

use App\Enums\FinancialStatus;
use App\Enums\FulfillmentStatus;
use App\Enums\OrderStatus;
use App\Enums\PaymentMethod;
use App\Models\Concerns\BelongsToStore;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

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

    /**
     * @var list<string>
     */
    protected $fillable = [
        'store_id',
        'checkout_id',
        'customer_id',
        'order_number',
        'payment_method',
        'status',
        'financial_status',
        'fulfillment_status',
        'currency',
        'subtotal_amount',
        'discount_amount',
        'shipping_amount',
        'tax_amount',
        'total_amount',
        'email',
        'billing_address_json',
        'shipping_address_json',
        'placed_at',
    ];

    /**
     * @var array<string, mixed>
     */
    protected $attributes = [
        'status' => 'pending',
        'financial_status' => 'pending',
        'fulfillment_status' => 'unfulfilled',
        'currency' => 'USD',
        'subtotal_amount' => 0,
        'discount_amount' => 0,
        'shipping_amount' => 0,
        'tax_amount' => 0,
        'total_amount' => 0,
    ];

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

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

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

    /**
     * @return HasMany<OrderLine, $this>
     */
    public function lines(): HasMany
    {
        return $this->hasMany(OrderLine::class);
    }

    /**
     * @return HasMany<Payment, $this>
     */
    public function payments(): HasMany
    {
        return $this->hasMany(Payment::class);
    }

    /**
     * @return HasMany<Refund, $this>
     */
    public function refunds(): HasMany
    {
        return $this->hasMany(Refund::class);
    }

    /**
     * @return HasMany<Fulfillment, $this>
     */
    public function fulfillments(): HasMany
    {
        return $this->hasMany(Fulfillment::class);
    }

    /**
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            'payment_method' => PaymentMethod::class,
            'status' => OrderStatus::class,
            'financial_status' => FinancialStatus::class,
            'fulfillment_status' => FulfillmentStatus::class,
            'subtotal_amount' => 'integer',
            'discount_amount' => 'integer',
            'shipping_amount' => 'integer',
            'tax_amount' => 'integer',
            'total_amount' => 'integer',
            'billing_address_json' => 'array',
            'shipping_address_json' => 'array',
            'placed_at' => 'datetime',
        ];
    }
}


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

aggregated_output:
<?php

namespace App\Livewire\Storefront\Cart;

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

class Show extends Component
{
    public int $storeId;

    public string $discountCode = '';

    public ?string $appliedDiscountCode = null;

    public string $shippingCountry = 'DE';

    public string $shippingPostalCode = '';

    public string $shippingProvinceCode = '';

    public ?string $cartMessage = null;

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

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

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

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

        try {
            app(CartService::class)->updateLineQuantity($line->cart, $line->getKey(), $line->quantity + 1);
            $this->cartMessage = null;
            $this->dispatch('cart-updated');
        } catch (InsufficientInventoryException|InvalidCartOperationException $exception) {
            $this->cartMessage = $exception->getMessage();
        }
    }

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

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

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

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

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

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

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

        $cart = $this->cart();

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

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

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

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

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

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

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

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

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

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

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

            return $store;
        }

        $store = app('current_store');

        abort_unless($store instanceof Store, 404);

        return $store;
    }

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

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

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

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

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

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

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

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

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

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


command: sed -n '1,260p' app/Http/Controllers/Api/Storefront/V1/CheckoutController.php

aggregated_output:
<?php

namespace App\Http\Controllers\Api\Storefront\V1;

use App\Exceptions\InsufficientInventoryException;
use App\Exceptions\InvalidCheckoutTransitionException;
use App\Exceptions\InvalidDiscountException;
use App\Exceptions\PaymentFailedException;
use App\Exceptions\UnserviceableShippingAddressException;
use App\Http\Controllers\Controller;
use App\Http\Requests\Api\Storefront\V1\ApplyCheckoutDiscountRequest;
use App\Http\Requests\Api\Storefront\V1\CompleteCheckoutPaymentRequest;
use App\Http\Requests\Api\Storefront\V1\SelectCheckoutPaymentRequest;
use App\Http\Requests\Api\Storefront\V1\SetCheckoutAddressRequest;
use App\Http\Requests\Api\Storefront\V1\SetCheckoutShippingRequest;
use App\Http\Requests\Api\Storefront\V1\StoreCheckoutRequest;
use App\Http\Resources\Storefront\V1\CheckoutResource;
use App\Http\Resources\Storefront\V1\OrderResource;
use App\Models\Cart;
use App\Models\Checkout;
use App\Models\Order;
use App\Models\ShippingRate;
use App\Services\CheckoutService;
use App\Services\PricingEngine;
use App\Services\ShippingCalculator;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Collection;

class CheckoutController extends Controller
{
    public function store(StoreCheckoutRequest $request, CheckoutService $checkouts, PricingEngine $pricing): CheckoutResource|JsonResponse
    {
        $cart = Cart::query()->findOrFail($request->validated('cart_id'));

        try {
            $checkout = $checkouts->createFromCart($cart);
            $checkout->forceFill([
                'email' => (string) $request->validated('email'),
            ])->save();
            $pricing->calculate($checkout);

            return CheckoutResource::make($this->loadCheckout(
                $checkout->refresh(),
            ))->response()->setStatusCode(201);
        } catch (InvalidCheckoutTransitionException $exception) {
            return response()->json(['message' => $exception->getMessage()], 422);
        }
    }

    public function show(Checkout $checkout): CheckoutResource
    {
        return CheckoutResource::make($this->loadCheckout($checkout));
    }

    public function address(SetCheckoutAddressRequest $request, Checkout $checkout, CheckoutService $checkouts): CheckoutResource|JsonResponse
    {
        $addressData = $request->validated();
        $addressData['email'] ??= $checkout->email;

        try {
            return CheckoutResource::make($this->loadCheckout($checkouts->setAddress($checkout, $addressData)));
        } catch (InvalidCheckoutTransitionException $exception) {
            return response()->json(['message' => $exception->getMessage()], 422);
        }
    }

    public function shippingMethod(SetCheckoutShippingRequest $request, Checkout $checkout, CheckoutService $checkouts): CheckoutResource|JsonResponse
    {
        try {
            return CheckoutResource::make($this->loadCheckout($checkouts->setShippingMethod(
                $checkout,
                $request->validated('shipping_rate_id'),
            )));
        } catch (InvalidCheckoutTransitionException|UnserviceableShippingAddressException $exception) {
            return response()->json(['message' => $exception->getMessage()], 422);
        }
    }

    public function applyDiscount(ApplyCheckoutDiscountRequest $request, Checkout $checkout, PricingEngine $pricing): CheckoutResource|JsonResponse
    {
        $checkout->forceFill([
            'discount_code' => trim((string) $request->validated('code')) ?: null,
        ])->save();

        try {
            $pricing->calculate($checkout);

            return CheckoutResource::make($this->loadCheckout($checkout->refresh()));
        } catch (InvalidDiscountException $exception) {
            $checkout->forceFill(['discount_code' => null])->save();
            $pricing->calculate($checkout);

            return response()->json([
                'message' => $exception->getMessage(),
                'reason' => $exception->reasonCode,
            ], 422);
        }
    }

    public function destroyDiscount(Checkout $checkout, PricingEngine $pricing): CheckoutResource
    {
        abort_if($checkout->discount_code === null, 404);

        $checkout->forceFill(['discount_code' => null])->save();
        $pricing->calculate($checkout);

        return CheckoutResource::make($this->loadCheckout($checkout->refresh()));
    }

    public function paymentMethod(SelectCheckoutPaymentRequest $request, Checkout $checkout, CheckoutService $checkouts): CheckoutResource|JsonResponse
    {
        try {
            return CheckoutResource::make($this->loadCheckout($checkouts->selectPaymentMethod(
                $checkout,
                (string) $request->validated('payment_method'),
            )));
        } catch (InsufficientInventoryException|InvalidCheckoutTransitionException $exception) {
            return response()->json(['message' => $exception->getMessage()], 422);
        }
    }

    public function pay(CompleteCheckoutPaymentRequest $request, Checkout $checkout, CheckoutService $checkouts): OrderResource|JsonResponse
    {
        try {
            if ($checkout->payment_method !== $request->validated('payment_method')) {
                $checkout = $checkouts->selectPaymentMethod($checkout, (string) $request->validated('payment_method'));
            }

            $order = $checkouts->completeCheckout($checkout, [
                'card_number' => $request->validated('card_number'),
                'cardholder_name' => $request->validated('card_holder'),
                'expiry' => $request->validated('card_expiry'),
                'cvc' => $request->validated('card_cvc'),
            ]);

            return OrderResource::make($this->loadOrder($order))
                ->response()
                ->setStatusCode(200);
        } catch (PaymentFailedException $exception) {
            return response()->json(['message' => $exception->getMessage()], 402);
        } catch (InsufficientInventoryException|InvalidCheckoutTransitionException $exception) {
            return response()->json(['message' => $exception->getMessage()], 422);
        }
    }

    private function loadCheckout(Checkout $checkout): Checkout
    {
        $checkout = $checkout->load([
            'cart.lines.variant.product',
            'cart.lines.variant.optionValues.option',
            'store',
        ]);

        $checkout->setRelation('availableRates', $this->availableRates($checkout));

        return $checkout;
    }

    private function loadOrder(Order $order): Order
    {
        return $order->load(['lines', 'payments', 'fulfillments.lines']);
    }

    /**
     * @return Collection<int, ShippingRate>
     */
    private function availableRates(Checkout $checkout): Collection
    {
        if (! is_array($checkout->shipping_address_json) || $checkout->shipping_address_json === []) {
            return collect();
        }

        return app(ShippingCalculator::class)
            ->getAvailableRates($checkout->store, $checkout->shipping_address_json)
            ->map(function (ShippingRate $rate) use ($checkout): ShippingRate {
                $rate->setAttribute('calculated_amount', app(ShippingCalculator::class)->calculate($rate, $checkout->cart));

                return $rate;
            });
    }
}


command:
/bin/zsh
-lc
sed -n '1,200p' app/Models/Cart.php

Cart.php

cmd: sed -n '1,200p' app/Models/Cart.php

aggregated_output:
<?php

namespace App\Models;

use App\Enums\CartStatus;
use App\Models\Concerns\BelongsToStore;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

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

    /**
     * @var list<string>
     */
    protected $fillable = [
        'store_id',
        'customer_id',
        'currency',
        'cart_version',
        'status',
    ];

    /**
     * @var array<string, mixed>
     */
    protected $attributes = [
        'currency' => 'USD',
        'cart_version' => 1,
        'status' => 'active',
    ];

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

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

    /**
     * @return HasMany<CartLine, $this>
     */
    public function lines(): HasMany
    {
        return $this->hasMany(CartLine::class);
    }

    /**
     * @return HasMany<Checkout, $this>
     */
    public function checkouts(): HasMany
    {
        return $this->hasMany(Checkout::class);
    }

    /**
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            'cart_version' => 'integer',
            'status' => CartStatus::class,
        ];
    }
}


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

namespace App\Models;

use App\Enums\CartStatus;
use App\Models\Concerns\BelongsToStore;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

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

    /**
     * @var list<string>
     */
    protected $fillable = [
        'store_id',
        'customer_id',
        'currency',
        'cart_version',
        'status',
    ];

    /**
     * @var array<string, mixed>
     */
    protected $attributes = [
        'currency' => 'USD',
        'cart_version' => 1,
        'status' => 'active',
    ];

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

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

    /**
     * @return HasMany<CartLine, $this>
     */
    public function lines(): HasMany
    {
        return $this->hasMany(CartLine::class);
    }

    /**
     * @return HasMany<Checkout, $this>
     */
    public function checkouts(): HasMany
    {
        return $this->hasMany(Checkout::class);
    }

    /**
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            'cart_version' => 'integer',
            'status' => CartStatus::class,
        ];
    }
}


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

namespace App\Http\Controllers\Api\Storefront\V1;

use App\Exceptions\InsufficientInventoryException;
use App\Exceptions\InvalidCheckoutTransitionException;
use App\Exceptions\InvalidDiscountException;
use App\Exceptions\PaymentFailedException;
use App\Exceptions\UnserviceableShippingAddressException;
use App\Http\Controllers\Controller;
use App\Http\Requests\Api\Storefront\V1\ApplyCheckoutDiscountRequest;
use App\Http\Requests\Api\Storefront\V1\CompleteCheckoutPaymentRequest;
use App\Http\Requests\Api\Storefront\V1\SelectCheckoutPaymentRequest;
use App\Http\Requests\Api\Storefront\V1\SetCheckoutAddressRequest;
use App\Http\Requests\Api\Storefront\V1\SetCheckoutShippingRequest;
use App\Http\Requests\Api\Storefront\V1\StoreCheckoutRequest;
use App\Http\Resources\Storefront\V1\CheckoutResource;
use App\Http\Resources\Storefront\V1\OrderResource;
use App\Models\Cart;
use App\Models\Checkout;
use App\Models\Order;
use App\Models\ShippingRate;
use App\Services\CheckoutService;
use App\Services\PricingEngine;
use App\Services\ShippingCalculator;
use Illuminate\Http\JsonResponse;
use Illuminate\Support\Collection;

class CheckoutController extends Controller
{
    public function store(StoreCheckoutRequest $request, CheckoutService $checkouts, PricingEngine $pricing): CheckoutResource|JsonResponse
    {
        $cart = Cart::query()->findOrFail($request->validated('cart_id'));

        try {
            $checkout = $checkouts->createFromCart($cart);
            $checkout->forceFill([
                'email' => (string) $request->validated('email'),
            ])->save();
            $pricing->calculate($checkout);

            return CheckoutResource::make($this->loadCheckout(
                $checkout->refresh(),
            ))->response()->setStatusCode(201);
        } catch (InvalidCheckoutTransitionException $exception) {
            return response()->json(['message' => $exception->getMessage()], 422);
        }
    }

    public function show(Checkout $checkout): CheckoutResource
    {
        return CheckoutResource::make($this->loadCheckout($checkout));
    }

    public function address(SetCheckoutAddressRequest $request, Checkout $checkout, CheckoutService $checkouts): CheckoutResource|JsonResponse
    {
        $addressData = $request->validated();
        $addressData['email'] ??= $checkout->email;

        try {
            return CheckoutResource::make($this->loadCheckout($checkouts->setAddress($checkout, $addressData)));
        } catch (InvalidCheckoutTransitionException $exception) {
            return response()->json(['message' => $exception->getMessage()], 422);
        }
    }

    public function shippingMethod(SetCheckoutShippingRequest $request, Checkout $checkout, CheckoutService $checkouts): CheckoutResource|JsonResponse
    {
        try {
            return CheckoutResource::make($this->loadCheckout($checkouts->setShippingMethod(
                $checkout,
                $request->validated('shipping_rate_id'),
            )));
        } catch (InvalidCheckoutTransitionException|UnserviceableShippingAddressException $exception) {
            return response()->json(['message' => $exception->getMessage()], 422);
        }
    }

    public function applyDiscount(ApplyCheckoutDiscountRequest $request, Checkout $checkout, PricingEngine $pricing): CheckoutResource|JsonResponse
    {
        $checkout->forceFill([
            'discount_code' => trim((string) $request->validated('code')) ?: null,
        ])->save();

        try {
            $pricing->calculate($checkout);

            return CheckoutResource::make($this->loadCheckout($checkout->refresh()));
        } catch (InvalidDiscountException $exception) {
            $checkout->forceFill(['discount_code' => null])->save();
            $pricing->calculate($checkout);

            return response()->json([
                'message' => $exception->getMessage(),
                'reason' => $exception->reasonCode,
            ], 422);
        }
    }

    public function destroyDiscount(Checkout $checkout, PricingEngine $pricing): CheckoutResource
    {
        abort_if($checkout->discount_code === null, 404);

        $checkout->forceFill(['discount_code' => null])->save();
        $pricing->calculate($checkout);

        return CheckoutResource::make($this->loadCheckout($checkout->refresh()));
    }

    public function paymentMethod(SelectCheckoutPaymentRequest $request, Checkout $checkout, CheckoutService $checkouts): CheckoutResource|JsonResponse
    {
        try {
            return CheckoutResource::make($this->loadCheckout($checkouts->selectPaymentMethod(
                $checkout,
                (string) $request->validated('payment_method'),
            )));
        } catch (InsufficientInventoryException|InvalidCheckoutTransitionException $exception) {
            return response()->json(['message' => $exception->getMessage()], 422);
        }
    }

    public function pay(CompleteCheckoutPaymentRequest $request, Checkout $checkout, CheckoutService $checkouts): OrderResource|JsonResponse
    {
        try {
            if ($checkout->payment_method !== $request->validated('payment_method')) {
                $checkout = $checkouts->selectPaymentMethod($checkout, (string) $request->validated('payment_method'));
            }

            $order = $checkouts->completeCheckout($checkout, [
                'card_number' => $request->validated('card_number'),
                'cardholder_name' => $request->validated('card_holder'),
                'expiry' => $request->validated('card_expiry'),
                'cvc' => $request->validated('card_cvc'),
            ]);

            return OrderResource::make($this->loadOrder($order))
                ->response()
                ->setStatusCode(200);
        } catch (PaymentFailedException $exception) {
            return response()->json(['message' => $exception->getMessage()], 402);
        } catch (InsufficientInventoryException|InvalidCheckoutTransitionException $exception) {
            return response()->json(['message' => $exception->getMessage()], 422);
        }
    }

    private function loadCheckout(Checkout $checkout): Checkout
    {
        $checkout = $checkout->load([
            'cart.lines.variant.product',
            'cart.lines.variant.optionValues.option',
            'store',
        ]);

        $checkout->setRelation('availableRates', $this->availableRates($checkout));

        return $checkout;
    }

    private function loadOrder(Order $order): Order
    {
        return $order->load(['lines', 'payments', 'fulfillments.lines']);
    }

    /**
     * @return Collection<int, ShippingRate>
     */
    private function availableRates(Checkout $checkout): Collection
    {
        if (! is_array($checkout->shipping_address_json) || $checkout->shipping_address_json === []) {
            return collect();
        }

        return app(ShippingCalculator::class)
            ->getAvailableRates($checkout->store, $checkout->shipping_address_json)
            ->map(function (ShippingRate $rate) use ($checkout): ShippingRate {
                $rate->setAttribute('calculated_amount', app(ShippingCalculator::class)->calculate($rate, $checkout->cart));

                return $rate;
            });
    }
}


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

namespace App\Livewire\Storefront\Cart;

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

class Show extends Component
{
    public int $storeId;

    public string $discountCode = '';

    public ?string $appliedDiscountCode = null;

    public string $shippingCountry = 'DE';

    public string $shippingPostalCode = '';

    public string $shippingProvinceCode = '';

    public ?string $cartMessage = null;

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

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

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

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

        try {
            app(CartService::class)->updateLineQuantity($line->cart, $line->getKey(), $line->quantity + 1);
            $this->cartMessage = null;
            $this->dispatch('cart-updated');
        } catch (InsufficientInventoryException|InvalidCartOperationException $exception) {
            $this->cartMessage = $exception->getMessage();
        }
    }

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

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

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

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

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

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

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

        $cart = $this->cart();

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

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

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

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

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

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

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

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

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

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

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

            return $store;
        }

        $store = app('current_store');

        abort_unless($store instanceof Store, 404);

        return $store;
    }

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

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

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

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

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

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

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

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

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

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


command: sed -n '1,110p' app/Livewire/Storefront/CartDrawer.php

aggregated_output:
<?php

namespace App\Livewire\Storefront;

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

class CartDrawer extends Component
{
    public int $storeId;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            return $store;
        }

        $store = app('current_store');

        abort_unless($store instanceof Store, 404);

        return $store;
    }

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

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

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

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


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

namespace App\Livewire\Storefront;

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

class CartDrawer extends Component
{
    public int $storeId;

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

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

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

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

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

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

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

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

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

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

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

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

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

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

            return $store;
        }

        $store = app('current_store');

        abort_unless($store instanceof Store, 404);

        return $store;
    }

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

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

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

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


cmd: sed -n '1,470p' app/Livewire/Storefront/Checkout/Show.php


cmd: sed -n '1,180p' app/Livewire/Storefront/Checkout/Confirmation.php


cmd: sed -n '1,220p' resources/views/livewire/storefront/checkout/confirmation.blade.php


cmd: sed -n '1,260p' tests/Feature/Checkout/CheckoutServiceTest.php


cmd: sed -n '1,280p' tests/Feature/Checkout/OrderServiceTest.php


cmd: rg -n "checkout.confirmation|checkout.show|/checkout/confirmation|/checkout/\{|checkout/\{checkout|confirmation" tests app resources routes specs