Output:
Chunk ID: 8ffecb
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 14541
Output:
Total output lines: 555

app/Services/VariantMatrixService.php:167:    private function createVariantFromTemplate(Product $product, ?ProductVariant $template, int $position): ProductVariant
tests/Feature/Api/StorefrontCheckoutApiTest.php:64:test('storefront checkout api progresses through address shipping discount removal and payment selection', function (): void {
tests/Feature/Api/StorefrontCheckoutApiTest.php:80:    $checkoutResponse = $api()
tests/Feature/Api/StorefrontCheckoutApiTest.php:81:        ->postJson('/api/storefront/v1/checkouts', [
tests/Feature/Api/StorefrontCheckoutApiTest.php:86:    $checkoutResponse
tests/Feature/Api/StorefrontCheckoutApiTest.php:93:    $checkoutId = $checkoutResponse['data']['id'];
tests/Feature/Api/StorefrontCheckoutApiTest.php:96:        ->putJson("/api/storefront/v1/checkouts/{$checkoutId}/address", [
tests/Feature/Api/StorefrontCheckoutApiTest.php:109:        ->putJson("/api/storefront/v1/checkouts/{$checkoutId}/shipping-method", [
tests/Feature/Api/StorefrontCheckoutApiTest.php:118:        ->postJson("/api/storefront/v1/checkouts/{$checkoutId}/apply-discount", ['code' => 'SAVE10'])
tests/Feature/Api/StorefrontCheckoutApiTest.php:124:        ->deleteJson("/api/storefront/v1/checkouts/{$checkoutId}/discount")
tests/Feature/Api/StorefrontCheckoutApiTest.php:130:        ->putJson("/api/storefront/v1/checkouts/{$checkoutId}/payment-method", [
tests/Feature/Api/StorefrontCheckoutApiTest.php:137:    $checkout = Checkout::withoutGlobalScopes()->findOrFail($checkoutId);
tests/Feature/Api/StorefrontCheckoutApiTest.php:140:    expect($checkout->status)->toBe(CheckoutStatus::PaymentSelected)
tests/Feature/Api/StorefrontCheckoutApiTest.php:144:test('storefront checkout api rejects invalid addresses shipping methods and discounts', function (): void {
tests/Feature/Api/StorefrontCheckoutApiTest.php:160:    $checkoutId = $api()
tests/Feature/Api/StorefrontCheckoutApiTest.php:161:        ->postJson('/api/storefront/v1/checkouts', [
tests/Feature/Api/StorefrontCheckoutApiTest.php:168:        ->putJson("/api/storefront/v1/checkouts/{$checkoutId}/address", [
tests/Feature/Api/StorefrontCheckoutApiTest.php:175:        ->putJson("/api/storefront/v1/checkouts/{$checkoutId}/address", [
tests/Feature/Api/StorefrontCheckoutApiTest.php:185:        ->putJson("/api/storefront/v1/checkouts/{$checkoutId}/shipping-method", [
tests/Feature/Api/StorefrontCheckoutApiTest.php:191:        ->postJson("/api/storefront/v1/checkouts/{$checkoutId}/apply-discount", ['code' => 'NOTREAL'])
routes/api.php:54:        Route::middleware('throttle:checkout')->group(function (): void {
routes/api.php:55:            Route::post('checkouts', [CheckoutController::class, 'store'])->name('checkouts.store');
routes/api.php:56:            Route::get('checkouts/{checkout}', [CheckoutController::class, 'show'])->name('checkouts.show');
routes/api.php:57:            Route::put('checkouts/{checkout}/address', [CheckoutController::class, 'address'])->name('checkouts.address');
routes/api.php:58:            Route::put('checkouts/{checkout}/shipping-method', [CheckoutController::class, 'shippingMethod'])->name('checkouts.shipping-method');
routes/api.php:59:            Route::post('checkouts/{checkout}/apply-discount', [CheckoutController::class, 'applyDiscount'])->name('checkouts.apply-discount');
routes/api.php:60:            Route::delete('checkouts/{checkout}/discount', [CheckoutController::class, 'destroyDiscount'])->name('checkouts.discount.destroy');
routes/api.php:61:            Route::put('checkouts/{checkout}/payment-method', [CheckoutController::class, 'paymentMethod'])->name('checkouts.payment-method');
routes/api.php:62:            Route::post('checkouts/{checkout}/pay', [CheckoutController::class, 'pay'])->name('checkouts.pay');
app/Services/SearchService.php:167:    public function syncProduct(Product $product): void
app/Livewire/Admin/Developers/Index.php:17:class Index extends Component
app/Livewire/Admin/Developers/Index.php:47:    public function mount(): void
app/Livewire/Admin/Developers/Index.php:99:    public function saveWebhook(WebhookService $webhooks): void
app/Livewire/Admin/Developers/Index.php:130:    public function deleteWebhook(int $webhookId): void
tests/Feature/Checkout/PricingServicesTest.php:107:    $checkout = pricingCheckout($store, $variant);
tests/Feature/Checkout/PricingServicesTest.php:108:    $checkout->forceFill(['shipping_method_id' => $rate->getKey()])->save();
tests/Feature/Checkout/PricingServicesTest.php:110:    $result = app(PricingEngine::class)->calculate($checkout);
tests/Feature/Checkout/PricingServicesTest.php:116:        ->and($checkout->refresh()->totals_json['total'])->toBe(6544);
tests/Feature/Checkout/PricingServicesTest.php:137:    $checkout = pricingCheckout($store, $variant);
tests/Feature/Checkout/PricingServicesTest.php:138:    $checkout->forceFill([
tests/Feature/Checkout/PricingServicesTest.php:143:    $discounted = app(PricingEngine::class)->calculate($checkout);
tests/Feature/Checkout/PricingServicesTest.php:149:    $checkout->forceFill(['discount_code' => 'FREESHIP'])->save();
tests/Feature/Checkout/PricingServicesTest.php:150:    $freeShipping = app(PricingEngine::class)->calculate($checkout);
tests/Feature/Checkout/PricingServicesTest.php:160:    $checkout = pricingCheckout($store, $variant);
tests/Feature/Checkout/PricingServicesTest.php:169:    $result = app(PricingEngine::class)->calculate($checkout);
tests/Feature/Checkout/PricingServicesTest.php:170:    $line = $checkout->cart->lines()->firstOrFail();
tests/Feature/Checkout/PricingServicesTest.php:181:    $checkout = pricingCheckout($store, $variant);
tests/Feature/Checkout/PricingServicesTest.php:195:    $checkout->forceFill(['discount_code' => 'SAVE10'])->save();
tests/Feature/Checkout/PricingServicesTest.php:197:    $result = app(PricingEngine::class)->calculate($checkout);
tests/Feature/Checkout/PricingServicesTest.php:198:    $line = $checkout->cart->lines()->firstOrFail();
app/Services/OrderExportService.php:19:    public function create(Store $store, array $filters): DataExport
app/Livewire/Admin/Analytics/Index.php:23:class Index extends Component
app/Livewire/Admin/Analytics/Index.php:54:    public int $checkoutStartedCount = 0;
app/Livewire/Admin/Analytics/Index.php:56:    public int $checkoutCompletedCount = 0;
app/Livewire/Admin/Analytics/Index.php:79:    public function mount(AnalyticsService $analytics): void
app/Livewire/Admin/Analytics/Index.php:92:    public function updatedDateRange(AnalyticsService $analytics): void
app/Livewire/Admin/Analytics/Index.php:97:    public function updatedCustomStartDate(AnalyticsService $analytics): void
app/Livewire/Admin/Analytics/Index.php:104:    public function updatedCustomEndDate(AnalyticsService $analytics): void
app/Livewire/Admin/Analytics/Index.php:111:    public function updatedChannelFilter(AnalyticsService $analytics): void
app/Livewire/Admin/Analytics/Index.php:116:    public function updatedDeviceFilter(AnalyticsService $analytics): void
app/Livewire/Admin/Analytics/Index.php:132:            ? round(($totals['checkout_completed_count'] / $totals['visits_count']) * 100, 2)
app/Livewire/Admin/Analytics/Index.php:136:        $this->checkoutStartedCount = $totals['checkout_started_count'];
app/Livewire/Admin/Analytics/Index.php:137:        $this->checkoutCompletedCount = $totals['checkout_completed_count'];
routes/web.php:56:    Route::livewire('/', StorefrontHome::class)->name('home');
routes/web.php:57:    Route::livewire('collections', StorefrontCollectionsIndex::class)->name('collections.index');
routes/web.php:58:    Route::livewire('collections/{handle}', StorefrontCollectionShow::class)->name('collections.show');
routes/web.php:59:    Route::livewire('products/{handle}', StorefrontProductShow::class)->name('products.show');
routes/web.php:60:    Route::livewire('cart', StorefrontCartShow::class)->name('cart.show');
routes/web.php:61:    Route::livewire('checkout', StorefrontCheckoutShow::class)->name('checkout.show');
routes/web.php:62:    Route::livewire('checkout/confirmation/{order}', StorefrontCheckoutConfirmation::class)->name('checkout.confirmation');
routes/web.php:63:    Route::livewire('search', StorefrontSearchIndex::class)->name('search.index');
routes/web.php:64:    Route::livewire('pages/{handle}', StorefrontPageShow::class)->name('pages.show');
routes/web.php:66:    Route::livewire('forgot-password', CustomerForgotPassword::class)
routes/web.php:74:    Route::livewire('reset-password/{token}', CustomerResetPassword::class)
routes/web.php:83:Route::livewire('admin/login', AdminLogin::class)
routes/web.php:120:    Route::livewire('/', AdminDashboard::class)->name('dashboard');
routes/web.php:121:    Route::livewire('analytics', AdminAnalyticsIndex::class)->name('analytics.index');
routes/web.php:122:    Route::livewire('apps', AdminAppsIndex::class)->name('apps.index');
routes/web.php:123:    Route::livewire('apps/{installation}', AdminAppShow::class)->name('apps.show');
routes/web.php:124:    Route::livewire('developers', AdminDevelopersIndex::class)->name('developers.index');
routes/web.php:125:    Route::livewire('products', AdminProductsIndex::class)->name('products.index');
routes/web.php:126:    Route::livewire('products/create', AdminProductForm::class)->name('products.create');
routes/web.php:127:    Route::livewire('products/{product}/edit', AdminProductForm::class)->name('products.edit');
routes/web.php:128:    Route::livewire('inventory', AdminInventoryIndex::class)->name('inventory.index');
routes/web.php:129:    Route::livewire('orders', AdminOrdersIndex::class)->name('orders.index');
routes/web.php:130:    Route::livewire('orders/{order}', AdminOrderShow::class)->name('orders.show');
routes/web.php:131:    Route::livewire('customers', AdminCustomersIndex::class)->name('customers.index');
routes/web.php:132:    Route::livewire('customers/{customer}', AdminCustomerShow::class)->name('customers.show');
routes/web.php:133:    Route::livewire('discounts', AdminDiscountsIndex::class)->name('discounts.index');
routes/web.php:134:    Route::livewire('discounts/create', AdminDiscountForm::class)->name('discounts.create');
routes/web.php:135:    Route::livewire('discounts/{discount}/edit', AdminDiscountForm::class)->name('discounts.edit');
routes/web.php:136:    Route::livewire('pages', AdminPagesIndex::class)->name('pages.index');
routes/web.php:137:    Route::livewire('pages/create', AdminPageForm::class)->name('pages.create');
routes/web.php:138:    Route::livewire('pages/{page}/edit', AdminPageForm::class)->name('pages.edit');
routes/web.php:139:    Route::livewire('navigation', AdminNavigationIndex::class)->name('navigation.index');
routes/web.php:140:    Route::livewire('themes', AdminThemesIndex::class)->name('themes.index');
routes/web.php:141:    Route::livewire('themes/{theme}/editor', AdminThemeEditor::class)->name('themes.editor');
routes/web.php:142:    Route::livewire('settings', AdminSettingsIndex::class)->name('settings.index');
routes/web.php:143:    Route::livewire('settings/shipping', AdminSettingsShipping::class)->name('settings.shipping');
routes/web.php:144:    Route::livewire('settings/taxes', AdminSettingsTaxes::class)->name('settings.taxes');
routes/web.php:145:    Route::livewire('settings/checkout', AdminSettingsCheckout::class)->name('settings.checkout');
routes/web.php:146:    Route::livewire('settings/notifications', AdminSettingsNotifications::class)->name('settings.notifications');
routes/web.php:147:    Route::livewire('search/settings', AdminSearchSettings::class)->name('search.settings');
routes/web.php:148:    Route::livewire('collections', AdminCollectionsIndex::class)->name('collections.index');
routes/web.php:149:    Route::livewire('collections/create', AdminCollectionForm::class)->name('collections.create');
routes/web.php:150:    Route::livewire('collections/{collection}/edit', AdminCollectionForm::class)->name('collections.edit');
routes/web.php:154:    Route::livewire('account/login', CustomerLogin::class)
routes/web.php:158:    Route::livewire('account/register', CustomerRegister::class)
routes/web.php:162:    Route::livewire('account/forgot-password', CustomerForgotPassword::class)
routes/web.php:166:    Route::livewire('account/reset-password/{token}', CustomerResetPassword::class)
routes/web.php:170:    Route::livewire('account', CustomerOrdersIndex::class)
routes/web.php:174:    Route::livewire('account/orders', CustomerOrdersIndex::class)
routes/web.php:178:    Route::livewire('account/orders/{order}', CustomerOrderShow::class)
routes/web.php:182:    Route::livewire('account/addresses', CustomerAddressesIndex::class)
app/Services/ThemeSettingsService.php:63:                'tagline' => 'A self-contained demo storefront with scoped catalog data and checkout-ready products.',
app/Livewire/Admin/Themes/Editor.php:33:    public function mount(Theme $theme, ThemeSettingsService $themeSettings): void
app/Livewire/Admin/Themes/Editor.php:70:    public function saveFile(): void
app/Livewire/Admin/Themes/Editor.php:92:    public function save(ThemeSettingsService $settings): void
app/Services/CustomerPasswordResetService.php:89:    private function deleteToken(Store $store, string $email): void
app/Services/ProductService.php:30:    public function create(Store $store, array $data): Product
app/Services/ProductService.php:84:    public function update(Product $product, array $data): Product
app/Services/ProductService.php:145:    public function delete(Product $product): void
app/Services/ProductService.php:157:    private function createVariant(Product $product, Store $store, array $variantData): ProductVariant
app/Services/ProductService.php:196:    private function syncVariantOptionValues(Product $product, ProductVariant $variant, array $variantData): void
app/Livewire/Admin/Themes/Index.php:18:class Index extends Component
app/Livewire/Admin/Themes/Index.php:25:    public function mount(): void
app/Livewire/Admin/Themes/Index.php:107:    public function deleteTheme(int $themeId): void
app/Services/PricingEngine.php:22:    public function calculate(Checkout $checkout): PricingResult
app/Services/PricingEngine.php:24:        return DB::transaction(function () use ($checkout): PricingResult {
app/Services/PricingEngine.php:25:            $checkout = Checkout::withoutGlobalScopes()
app/Services/PricingEngine.php:27:                ->whereKey($checkout->getKey())
app/Services/PricingEngine.php:29:            $cart = $checkout->cart;
app/Services/PricingEngine.php:31:            $this->resetLineAmounts($checkout);
app/Services/PricingEngine.php:41:            if ($checkout->discount_code) {
app/Services/PricingEngine.php:42:                $discount = $this->discounts->validate($checkout->discount_code, $checkout->store, $cart);
app/Services/PricingEngine.php:48:            foreach ($this->discounts->automaticForCart($checkout->store, $cart) as $discount) {
app/Services/PricingEngine.php:59:            $shippingAmount = $this->shippingAmount($checkout, $discountResult);
app/Services/PricingEngine.php:60:            $taxSettings = $this->taxSettings($checkout);
app/Services/PricingEngine.php:65:                $checkout->shipping_address_json ?? [],
app/Services/PricingEngine.php:82:            $checkout->forceFill([
app/Services/PricingEngine.php:91:    private function resetLineAmounts(Checkout $checkout): void
app/Services/PricingEngine.php:94:            ->where('cart_id', $checkout->cart_id)
app/Services/PricingEngine.php:107:    private function shippingAmount(Checkout $checkout, DiscountResult $discountResult): int
app/Services/PricingEngine.php:109:        if (! $this->shipping->requiresShipping($checkout->cart)) {
app/Services/PricingEngine.php:113:        if ($checkout->shipping_method_id === null) {
app/Services/PricingEngine.php:117:        $rate = ShippingRate::withoutGlobalScopes()->find($checkout->shipping_method_id);
app/Services/PricingEngine.php:123:        $amount = $this->shipping->calculate($rate, $checkout->cart);
app/Services/PricingEngine.php:132:    private function taxSettings(Checkout $checkout): TaxSettings
app/Services/PricingEngine.php:135:            ->where('store_id', $checkout->store_id)
app/Services/PricingEngine.php:137:                'store_id' => $checkout->store_id,
app/Services/RefundService.php:29:    public function process(Order $order, array $request = []): Refund
app/Services/RefundService.php:76:    private function refundablePayment(Order $order): Payment
app/Services/RefundService.php:90:    private function refundableAmount(Order $order): int
app/Services/RefundService.php:103:    private function refundAmount(Order $order, array $request, Collection $lineQuantities, int $refundable): int
app/Services/RefundService.php:184:    private function updateOrderFinancialStatus(Order $order, Payment $payment): void
tests/Feature/Checkout/CheckoutServiceTest.php:21:function checkoutStore(): Store
tests/Feature/Checkout/CheckoutServiceTest.php:37:function checkoutVariant(Store $store, bool $requiresShipping = true): ProductVariant
tests/Feature/Checkout/CheckoutServiceTest.php:60:function checkoutAddress(string $country = 'DE'): array
tests/Feature/Checkout/CheckoutServiceTest.php:75:test('checkout service transitions through address shipping payment and expiry', function () {
tests/Feature/Checkout/CheckoutServiceTest.php:76:    $store = checkoutStore();
tests/Feature/Checkout/CheckoutServiceTest.php:77:    $variant = checkoutVariant($store);
tests/Feature/Checkout/CheckoutServiceTest.php:93:    $checkout = app(CheckoutService::class)->createFromCart($cart);
tests/Feature/Checkout/CheckoutServiceTest.php:95:    $checkout = app(CheckoutService::class)->setAddress($checkout, checkoutAddress());
tests/Feature/Checkout/CheckoutServiceTest.php:96:    expect($checkout->status)->toBe(CheckoutStatus::Addressed)
tests/Feature/Checkout/CheckoutServiceTest.php:97:        ->and($checkout->email)->toBe('buyer@example.test');
tests/Feature/Checkout/CheckoutServiceTest.php:99:    $checkout = app(CheckoutService::class)->setShippingMethod($checkout, $rate->getKey());
tests/Feature/Checkout/CheckoutServiceTest.php:100:    expect($checkout->status)->toBe(CheckoutStatus::ShippingSelected)
tests/Feature/Checkout/CheckoutServiceTest.php:101:        ->and($checkout->shipping_method_id)->toBe($rate->getKey());
tests/Feature/Checkout/CheckoutServiceTest.php:103:    $checkout = app(CheckoutService::class)->selectPaymentMethod($checkout, 'credit_card');
tests/Feature/Checkout/CheckoutServiceTest.php:104:    expect($checkout->status)->toBe(CheckoutStatus::PaymentSelected)
tests/Feature/Checkout/CheckoutServiceTest.php:105:        ->and($checkout->expires_at)->not->toBeNull()
tests/Feature/Checkout/CheckoutServiceTest.php:108:    app(CheckoutService::class)->selectPaymentMethod($checkout, 'credit_card');
tests/Feature/Checkout/CheckoutServiceTest.php:111:    $expired = app(CheckoutService::class)->expireCheckout($checkout);
tests/Feature/Checkout/CheckoutServiceTest.php:116:test('checkout service rejects unserviceable shipping addresses for physical carts', function () {
tests/Feature/Checkout/CheckoutServiceTest.php:117:    $store = checkoutStore();
tests/Feature/Checkout/CheckoutServiceTest.php:118:    $variant = checkoutVariant($store);
tests/Feature/Checkout/CheckoutServiceTest.php:127:    $checkout = app(CheckoutService::class)->createFromCart($cart);
tests/Feature/Checkout/CheckoutServiceTest.php:128:    $checkout = app(CheckoutService::class)->setAddress($checkout, checkoutAddress('FR'));
tests/Feature/Checkout/CheckoutServiceTest.php:130:    expect(fn () => app(CheckoutService::class)->setShippingMethod($checkout, null))
tests/Feature/Checkout/CheckoutServiceTest.php:134:test('checkout service skips shipping for digital-only carts', function () {
tests/Feature/Checkout/CheckoutServiceTest.php:135:    $store = checkoutStore();
tests/Feature/Checkout/CheckoutServiceTest.php:136:    $variant = …4541 tokens truncated…/OrderService.php:121:                $checkout->forceFill([
app/Services/OrderService.php:126:                $this->incrementDiscountUsage($checkout);
app/Services/OrderService.php:133:                $checkout = $checkout->refresh();
app/Services/OrderService.php:136:                event(new CheckoutCompleted($checkout, $order));
app/Services/OrderService.php:145:            $this->releaseFailedPaymentReservation($checkout);
app/Services/OrderService.php:203:    private function freshCheckout(Checkout $checkout): Checkout
app/Services/OrderService.php:207:            ->whereKey($checkout->getKey())
app/Services/OrderService.php:221:    private function paymentMethod(Checkout $checkout): PaymentMethod
app/Services/OrderService.php:224:            return PaymentMethod::from((string) $checkout->payment_method);
app/Services/OrderService.php:258:    private function createOrderLines(Checkout $checkout, Order $order, array $discountAllocations): void
app/Services/OrderService.php:260:        $this->cartLines($checkout)->each(function (CartLine $line) use ($discountAllocations, $order): void {
app/Services/OrderService.php:292:    private function discountAllocationsByCartLine(Checkout $checkout): array
app/Services/OrderService.php:294:        $lines = $this->cartLines($checkout)
app/Services/OrderService.php:306:        foreach ($this->appliedDiscounts($checkout) as $discount) {
app/Services/OrderService.php:337:    private function appliedDiscounts(Checkout $checkout): Collection
app/Services/OrderService.php:340:        $code = trim((string) $checkout->discount_code);
app/Services/OrderService.php:344:                ->where('store_id', $checkout->store_id)
app/Services/OrderService.php:354:            ->merge($this->discounts->automaticForCart($checkout->store, $checkout->cart))
app/Services/OrderService.php:358:    private function commitReservedInventory(Checkout $checkout): void
app/Services/OrderService.php:360:        $this->cartLines($checkout)->each(function (CartLine $line): void {
app/Services/OrderService.php:383:    private function releaseFailedPaymentReservation(Checkout $checkout): void
app/Services/OrderService.php:385:        DB::transaction(function () use ($checkout): void {
app/Services/OrderService.php:386:            $checkout = $this->freshCheckout($checkout);
app/Services/OrderService.php:388:            if ($checkout->status !== CheckoutStatus::PaymentSelected) {
app/Services/OrderService.php:392:            $this->cartLines($checkout)->each(function (CartLine $line): void {
app/Services/OrderService.php:396:            $checkout->forceFill([
app/Services/OrderService.php:404:    private function incrementDiscountUsage(Checkout $checkout): void
app/Services/OrderService.php:406:        $code = trim((string) $checkout->discount_code);
app/Services/OrderService.php:413:            ->where('store_id', $checkout->store_id)
app/Services/OrderService.php:435:    private function cartLines(Checkout $checkout): Collection
app/Services/OrderService.php:444:            ->where('cart_id', $checkout->cart_id)
app/Livewire/Admin/Orders/Show.php:22:class Show extends Component
app/Livewire/Admin/Orders/Show.php:47:    public function mount(Order $order): void
app/Livewire/Admin/Orders/Show.php:79:    public function processRefund(RefundService $refunds): void
app/Livewire/Admin/Orders/Show.php:108:    public function createFulfillment(FulfillmentService $fulfillments): void
app/Livewire/Admin/Orders/Show.php:149:    public function markFulfillmentShipped(int $fulfillmentId, FulfillmentService $fulfillments): void
app/Livewire/Admin/Orders/Show.php:162:    public function markFulfillmentDelivered(int $fulfillmentId, FulfillmentService $fulfillments): void
app/Livewire/Admin/Orders/Show.php:203:    private function fulfillment(int $fulfillmentId): Fulfillment
app/Livewire/Admin/Orders/Show.php:233:    private function refundableAmount(Order $order): int
tests/Feature/Api/AdminStoreSettingsApiTest.php:59:                'checkout' => [
tests/Feature/Api/AdminStoreSettingsApiTest.php:72:        ->assertJsonPath('data.settings_json.checkout.terms_required', true)
tests/Feature/Api/AdminStoreSettingsApiTest.php:80:        ->and($settings->settings_json['checkout']['terms_url'])->toBe('https://example.test/terms')
tests/Feature/Api/AdminStoreSettingsApiTest.php:139:                'checkout' => [
tests/Feature/Api/AdminStoreSettingsApiTest.php:146:        ->assertJsonValidationErrors(['settings_json.checkout.terms_url', 'settings_json.checkout.payment_hold_hours']);
app/Services/WebhookService.php:65:    public function createApiToken(Store $store, string $name, array $abilities, ?User $user = null): array
app/Services/WebhookService.php:89:    public function createSigningSecret(): string
app/Livewire/Admin/Orders/Index.php:18:class Index extends Component
app/Livewire/Admin/Orders/Index.php:37:    public function mount(): void
app/Livewire/Admin/Orders/Index.php:46:    public function updatedSearch(): void
app/Livewire/Admin/Orders/Index.php:51:    public function updatedStatusFilter(): void
app/Livewire/Admin/Orders/Index.php:56:    public function updatedFinancialStatusFilter(): void
app/Livewire/Admin/Orders/Index.php:61:    public function updatedFulfillmentStatusFilter(): void
app/Livewire/Admin/Orders/Index.php:66:    public function updatedDateFrom(): void
app/Livewire/Admin/Orders/Index.php:71:    public function updatedDateTo(): void
app/Livewire/Admin/Navigation/Index.php:21:class Index extends Component
app/Livewire/Admin/Navigation/Index.php:47:    public function mount(): void
app/Livewire/Admin/Navigation/Index.php:94:    public function saveItem(): void
app/Livewire/Admin/Navigation/Index.php:214:    public function saveMenu(NavigationService $navigation): void
app/Livewire/Admin/Settings/Notifications.php:36:    public function mount(): void
app/Livewire/Admin/Settings/Notifications.php:46:    public function save(): void
app/Livewire/Admin/Settings/Checkout.php:38:    public function mount(): void
app/Livewire/Admin/Settings/Checkout.php:48:    public function save(): void
app/Livewire/Admin/Settings/Checkout.php:70:                'checkout' => [
app/Livewire/Admin/Settings/Checkout.php:71:                    'guest_checkout_enabled' => $validated['guestCheckoutEnabled'],
app/Livewire/Admin/Settings/Checkout.php:79:                    'abandoned_checkout_days' => $validated['abandonedCheckoutDays'],
app/Livewire/Admin/Settings/Checkout.php:92:        return view('livewire.admin.settings.checkout')
app/Livewire/Admin/Settings/Checkout.php:103:        $this->guestCheckoutEnabled = (bool) data_get($settings, 'checkout.guest_checkout_enabled', true);
app/Livewire/Admin/Settings/Checkout.php:104:        $this->customerAccountsRequired = (bool) data_get($settings, 'checkout.customer_accounts_required', false);
app/Livewire/Admin/Settings/Checkout.php:105:        $this->phoneNumberRequired = (bool) data_get($settings, 'checkout.phone_number_required', false);
app/Livewire/Admin/Settings/Checkout.php:106:        $this->billingAddressEnabled = (bool) data_get($settings, 'checkout.billing_address_enabled', true);
app/Livewire/Admin/Settings/Checkout.php:107:        $this->orderNotesEnabled = (bool) data_get($settings, 'checkout.order_notes_enabled', true);
app/Livewire/Admin/Settings/Checkout.php:108:        $this->termsRequired = (bool) data_get($settings, 'checkout.terms_required', false);
app/Livewire/Admin/Settings/Checkout.php:109:        $this->termsUrl = (string) data_get($settings, 'checkout.terms_url', '');
app/Livewire/Admin/Settings/Checkout.php:110:        $this->paymentHoldHours = (int) data_get($settings, 'checkout.payment_hold_hours', 24);
app/Livewire/Admin/Settings/Checkout.php:111:        $this->abandonedCheckoutDays = (int) data_get($settings, 'checkout.abandoned_checkout_days', 14);
app/Livewire/Storefront/Pages/Show.php:9:class Show extends Component
app/Livewire/Storefront/Pages/Show.php:17:    public function mount(string $handle): void
app/Livewire/Storefront/Collections/Show.php:13:class Show extends Component
app/Livewire/Storefront/Collections/Show.php:37:    public function mount(string $handle): void
app/Livewire/Storefront/Collections/Show.php:42:    public function updated(): void
app/Livewire/Storefront/Products/Show.php:15:class Show extends Component
app/Livewire/Storefront/Products/Show.php:28:    public function mount(string $handle): void
app/Livewire/Storefront/Collections/Index.php:9:class Index extends Component
app/Livewire/Storefront/CartDrawer.php:19:    public function mount(): void
app/Livewire/Storefront/CartDrawer.php:63:    public function checkout(): void
app/Livewire/Storefront/CartDrawer.php:69:        $this->redirectRoute('checkout.show', navigate: true);
app/Livewire/Storefront/Cart/Show.php:23:class Show extends Component
app/Livewire/Storefront/Cart/Show.php:39:    public function mount(): void
app/Livewire/Storefront/Cart/Show.php:142:    public function checkout(): void
app/Livewire/Storefront/Cart/Show.php:148:        $this->redirectRoute('checkout.show', navigate: true);
app/Livewire/Admin/Settings/Taxes.php:33:    public function mount(): void
app/Livewire/Admin/Settings/Taxes.php:59:    public function save(): void
app/Livewire/Storefront/Account/Orders/Show.php:12:class Show extends Component
app/Livewire/Storefront/Account/Orders/Show.php:20:    public function mount(Order $order): void
app/Livewire/Admin/Settings/Shipping.php:59:    public function mount(): void
app/Livewire/Admin/Settings/Shipping.php:79:    public function saveZone(): void
app/Livewire/Admin/Settings/Shipping.php:118:    public function deleteZone(int $zoneId): void
app/Livewire/Admin/Settings/Shipping.php:153:    public function saveRate(): void
app/Livewire/Admin/Settings/Shipping.php:195:    public function deleteRate(int $rateId): void
app/Livewire/Admin/Customers/Show.php:15:class Show extends Component
app/Livewire/Admin/Customers/Show.php:43:    public function mount(Customer $customer): void
app/Livewire/Admin/Customers/Show.php:75:    public function saveAddress(): void
app/Livewire/Admin/Customers/Show.php:105:    public function deleteAddress(int $addressId): void
app/Livewire/Storefront/Account/Auth/ForgotPassword.php:17:    public function mount(): void
app/Livewire/Admin/Customers/Index.php:13:class Index extends Component
app/Livewire/Admin/Customers/Index.php:24:    public function mount(): void
app/Livewire/Admin/Customers/Index.php:34:    public function updatedSearch(): void
app/Livewire/Admin/Settings/Index.php:15:class Index extends Component
app/Livewire/Admin/Settings/Index.php:42:    public function mount(): void
app/Livewire/Admin/Settings/Index.php:58:        $this->guestCheckoutEnabled = (bool) data_get($settings, 'checkout.guest_checkout_enabled', true);
app/Livewire/Admin/Settings/Index.php:61:    public function save(): void
app/Livewire/Admin/Settings/Index.php:91:                'checkout' => [
app/Livewire/Admin/Settings/Index.php:92:                    'guest_checkout_enabled' => $this->guestCheckoutEnabled,
app/Livewire/Storefront/Account/Auth/ResetPassword.php:24:    public function mount(string $token): void
tests/Feature/Api/StorefrontOrderApiTest.php:66:    $checkoutId = $api()
tests/Feature/Api/StorefrontOrderApiTest.php:67:        ->postJson('/api/storefront/v1/checkouts', [
tests/Feature/Api/StorefrontOrderApiTest.php:74:        ->putJson("/api/storefront/v1/checkouts/{$checkoutId}/address", [
tests/Feature/Api/StorefrontOrderApiTest.php:87:        ->putJson("/api/storefront/v1/checkouts/{$checkoutId}/shipping-method", [
tests/Feature/Api/StorefrontOrderApiTest.php:92:    return [$checkoutId, $variant];
tests/Feature/Api/StorefrontOrderApiTest.php:95:test('storefront order api pays a checkout and exposes token-gated order lookup', function (): void {
tests/Feature/Api/StorefrontOrderApiTest.php:96:    [$checkoutId] = storefrontOrderApiCheckout($this);
tests/Feature/Api/StorefrontOrderApiTest.php:100:        ->postJson("/api/storefront/v1/checkouts/{$checkoutId}/pay", [
tests/Feature/Api/StorefrontOrderApiTest.php:129:    [$checkoutId, $variant] = storefrontOrderApiCheckout($this, '10.0.0.42');
tests/Feature/Api/StorefrontOrderApiTest.php:133:        ->postJson("/api/storefront/v1/checkouts/{$checkoutId}/pay", [
tests/Feature/Api/StorefrontOrderApiTest.php:142:    $checkout = Checkout::withoutGlobalScopes()->findOrFail($checkoutId);
tests/Feature/Api/StorefrontOrderApiTest.php:145:    expect($checkout->status)->toBe(CheckoutStatus::ShippingSelected)
app/Livewire/Storefront/Search/Index.php:13:class Index extends Component
app/Livewire/Storefront/Search/Index.php:37:    public function mount(): void
app/Livewire/Storefront/Search/Index.php:42:    public function updated(): void
app/Livewire/Storefront/Account/Addresses/Index.php:14:class Index extends Component
app/Livewire/Storefront/Account/Addresses/Index.php:44:    public function mount(): void
app/Livewire/Storefront/Account/Addresses/Index.php:73:    public function saveAddress(): void
app/Livewire/Storefront/Account/Addresses/Index.php:103:    public function deleteAddress(int $addressId): void
app/Livewire/Storefront/Account/Orders/Index.php:13:class Index extends Component
app/Livewire/Storefront/Account/Orders/Index.php:21:    public function mount(): void
app/Livewire/Settings/Profile.php:23:    public function mount(): void
app/Livewire/Settings/Profile.php:32:    public function updateProfileInformation(): void
app/Livewire/Storefront/Checkout/Confirmation.php:20:    public function mount(Order $order): void
app/Livewire/Storefront/Checkout/Confirmation.php:46:        return view('livewire.storefront.checkout.confirmation', [
app/Livewire/Settings/TwoFactor.php:40:    public function mount(DisableTwoFactorAuthentication $disableTwoFactorAuthentication): void
app/Livewire/Storefront/Account/Auth/Register.php:25:    public function mount(): void
app/Livewire/Settings/Password.php:23:    public function updatePassword(): void
app/Livewire/Settings/DeleteUserForm.php:19:    public function deleteUser(Logout $logout): void
app/Livewire/Settings/TwoFactor/RecoveryCodes.php:18:    public function mount(): void
app/Livewire/Storefront/Account/Auth/Login.php:23:    public function mount(): void
app/Livewire/Storefront/Checkout/Show.php:27:class Show extends Component
app/Livewire/Storefront/Checkout/Show.php:80:    public function mount(): void
app/Livewire/Storefront/Checkout/Show.php:85:        $this->fillFromCheckout($this->checkout());
app/Livewire/Storefront/Checkout/Show.php:88:    public function saveAddress(): void
app/Livewire/Storefront/Checkout/Show.php:109:        $checkout = $this->checkout();
app/Livewire/Storefront/Checkout/Show.php:111:        if (! $checkout instanceof Checkout) {
app/Livewire/Storefront/Checkout/Show.php:116:            $checkout = app(CheckoutService::class)->setAddress($checkout, [
app/Livewire/Storefront/Checkout/Show.php:125:                app(CheckoutService::class)->setShippingMethod($checkout, null);
app/Livewire/Storefront/Checkout/Show.php:141:        $checkout = $this->checkout();
app/Livewire/Storefront/Checkout/Show.php:143:        if (! $checkout instanceof Checkout) {
app/Livewire/Storefront/Checkout/Show.php:154:            app(CheckoutService::class)->setShippingMethod($checkout, $this->selectedShippingRateId);
app/Livewire/Storefront/Checkout/Show.php:165:        $checkout = $this->checkout();
app/Livewire/Storefront/Checkout/Show.php:167:        if (! $checkout instanceof Checkout) {
app/Livewire/Storefront/Checkout/Show.php:171:        $checkout->forceFill([
app/Livewire/Storefront/Checkout/Show.php:176:            app(PricingEngine::class)->calculate($checkout);
app/Livewire/Storefront/Checkout/Show.php:179:            $checkout->forceFill(['discount_code' => null])->save();
app/Livewire/Storefront/Checkout/Show.php:181:            app(PricingEngine::class)->calculate($checkout);
app/Livewire/Storefront/Checkout/Show.php:195:        $checkout = $this->checkout();
app/Livewire/Storefront/Checkout/Show.php:197:        if (! $checkout instanceof Checkout) {
app/Livewire/Storefront/Checkout/Show.php:202:            app(CheckoutService::class)->selectPaymentMethod($checkout, $this->paymentMethod);
app/Livewire/Storefront/Checkout/Show.php:211:    public function placeOrder(): void
app/Livewire/Storefront/Checkout/Show.php:229:        $checkout = $this->checkout();
app/Livewire/Storefront/Checkout/Show.php:231:        if (! $checkout instanceof Checkout) {
app/Livewire/Storefront/Checkout/Show.php:236:            if ($checkout->status !== CheckoutStatus::PaymentSelected) {
app/Livewire/Storefront/Checkout/Show.php:237:                $checkout = app(CheckoutService::class)->selectPaymentMethod($checkout, $this->paymentMethod);
app/Livewire/Storefront/Checkout/Show.php:240:            $order = app(CheckoutService::class)->completeCheckout($checkout, [
app/Livewire/Storefront/Checkout/Show.php:252:            $this->redirectRoute('checkout.confirmation', ['order' => $order], navigate: true);
app/Livewire/Storefront/Checkout/Show.php:288:    public function checkout(): ?Checkout
app/Livewire/Storefront/Checkout/Show.php:296:        $checkout = Checkout::withoutGlobalScopes()
app/Livewire/Storefront/Checkout/Show.php:302:        if (! $checkout instanceof Checkout) {
app/Livewire/Storefront/Checkout/Show.php:303:            $checkout = app(CheckoutService::class)->createFromCart($cart, $this->customer());
app/Livewire/Storefront/Checkout/Show.php:306:        $checkout = $this->syncSessionDiscount($checkout);
app/Livewire/Storefront/Checkout/Show.php:308:        return $checkout->load(['cart.lines.variant.product', 'cart.lines.variant.optionValues.option']);
app/Livewire/Storefront/Checkout/Show.php:373:        return $this->checkout()?->totals_json ?? [
app/Livewire/Storefront/Checkout/Show.php:385:        return view('livewire.storefront.checkout.show', [
app/Livewire/Storefront/Checkout/Show.php:387:            'checkout' => $this->checkout(),
app/Livewire/Storefront/Checkout/Show.php:406:    private function fillFromCheckout(?Checkout $checkout): void
app/Livewire/Storefront/Checkout/Show.php:408:        if (! $checkout instanceof Checkout) {
app/Livewire/Storefront/Checkout/Show.php:412:        $this->email = $checkout->email ?: $this->email;
app/Livewire/Storefront/Checkout/Show.php:413:        $this->shippingAddress = array_replace($this->shippingAddress, $checkout->shipping_address_json ?? []);
app/Livewire/Storefront/Checkout/Show.php:414:        $this->billingAddress = array_replace($this->billingAddress, $checkout->billing_address_json ?? []);
app/Livewire/Storefront/Checkout/Show.php:415:        $this->selectedShippingRateId = $checkout->shipping_method_id;
app/Livewire/Storefront/Checkout/Show.php:416:        $this->discountCode = (string) ($checkout->discount_code ?? '');
app/Livewire/Storefront/Checkout/Show.php:417:        $this->paymentMethod = (string) ($checkout->payment_method ?? $this->paymentMethod);
app/Livewire/Storefront/Checkout/Show.php:418:        $this->step = match ($checkout->status) {
app/Livewire/Storefront/Checkout/Show.php:427:    private function syncSessionDiscount(Checkout $checkout): Checkout
app/Livewire/Storefront/Checkout/Show.php:431:        if ($code === '' || $checkout->discount_code !== null) {
app/Livewire/Storefront/Checkout/Show.php:432:            return $checkout;
app/Livewire/Storefront/Checkout/Show.php:435:        $checkout->forceFill(['discount_code' => $code])->save();
app/Livewire/Storefront/Checkout/Show.php:438:            app(PricingEngine::class)->calculate($checkout);
app/Livewire/Storefront/Checkout/Show.php:440:            $checkout->forceFill(['discount_code' => null])->save();
app/Livewire/Storefront/Checkout/Show.php:442:            app(PricingEngine::class)->calculate($checkout);
app/Livewire/Storefront/Checkout/Show.php:445:        return $checkout->refresh();


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

namespace App\Livewire\Admin\Orders;

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

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

    #[Locked]
    public int $orderId;

    public string $refundAmount = '';

    public string $refundReason = '';

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

    public string $trackingCompany = '';

    public string $trackingNumber = '';

    public string $trackingUrl = '';

    public string $actionMessage = '';

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

        abort_unless($store instanceof Store, 404);

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

        abort_unless($order instanceof Order, 404);

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

        abort_unless($fulfillment instanceof Fulfillment, 404);

        return $fulfillment;
    }

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

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

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

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

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


sed -n '1,300p' app/Services/CheckoutService.php

CheckoutService.php

<?php

namespace App\Services;

use App\Enums\CartStatus;
use App\Enums\CheckoutStatus;
use App\Exceptions\InvalidCheckoutTransitionException;
use App\Exceptions\UnserviceableShippingAddressException;
use App\Models\Cart;
use App\Models\CartLine;
use App\Models\Checkout;
use App\Models\Customer;
use App\Models\InventoryItem;
use App\Models\Order;
use App\Models\ShippingRate;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Validator;

class CheckoutService
{
    public function __construct(
        private readonly InventoryService $inventory,
        private readonly ShippingCalculator $shipping,
        private readonly PricingEngine $pricing,
        private readonly OrderService $orders,
    ) {}

    public function createFromCart(Cart $cart, ?Customer $customer = null): Checkout
    {
        $cart = Cart::withoutGlobalScopes()->findOrFail($cart->getKey());

        if ($cart->status !== CartStatus::Active) {
            throw InvalidCheckoutTransitionException::because('Checkout can only start from an active cart.');
        }

        if (! CartLine::withoutGlobalScopes()->where('cart_id', $cart->getKey())->exists()) {
            throw InvalidCheckoutTransitionException::because('Checkout cannot start from an empty cart.');
        }

        return Checkout::withoutGlobalScopes()->create([
            'store_id' => $cart->store_id,
            'cart_id' => $cart->getKey(),
            'customer_id' => $customer?->getKey() ?? $cart->customer_id,
            'status' => CheckoutStatus::Started,
        ]);
    }

    /**
     * @param  array<string, mixed>  $addressData
     */
    public function setAddress(Checkout $checkout, array $addressData): Checkout
    {
        return DB::transaction(function () use ($checkout, $addressData): Checkout {
            $checkout = $this->freshCheckout($checkout);
            $this->assertStatus($checkout, [CheckoutStatus::Started, CheckoutStatus::Addressed]);

            $email = (string) data_get($addressData, 'email');
            $shippingAddress = data_get($addressData, 'shipping_address', $addressData);

            Validator::make([
                'email' => $email,
                'shipping_address' => $shippingAddress,
            ], [
                'email' => ['required', 'email'],
                'shipping_address.first_name' => ['required', 'string'],
                'shipping_address.last_name' => ['required', 'string'],
                'shipping_address.address1' => ['required', 'string'],
                'shipping_address.city' => ['required', 'string'],
                'shipping_address.country' => ['required', 'string', 'size:2'],
                'shipping_address.postal_code' => ['required', 'string'],
            ])->validate();

            $checkout->forceFill([
                'email' => $email,
                'shipping_address_json' => $shippingAddress,
                'billing_address_json' => data_get($addressData, 'billing_address', $shippingAddress),
                'status' => CheckoutStatus::Addressed,
            ])->save();

            $this->pricing->calculate($checkout);

            return $checkout->refresh();
        });
    }

    public function setShippingMethod(Checkout $checkout, ?int $shippingRateId): Checkout
    {
        return DB::transaction(function () use ($checkout, $shippingRateId): Checkout {
            $checkout = $this->freshCheckout($checkout);
            $this->assertStatus($checkout, [CheckoutStatus::Addressed, CheckoutStatus::ShippingSelected]);

            if (! $this->shipping->requiresShipping($checkout->cart)) {
                $checkout->forceFill([
                    'shipping_method_id' => null,
                    'status' => CheckoutStatus::ShippingSelected,
                ])->save();

                $this->pricing->calculate($checkout);

                return $checkout->refresh();
            }

            $availableRates = $this->shipping->getAvailableRates($checkout->store, $checkout->shipping_address_json ?? []);

            if ($availableRates->isEmpty()) {
                throw UnserviceableShippingAddressException::forAddress();
            }

            $rate = $availableRates->firstWhere('id', $shippingRateId);

            if (! $rate instanceof ShippingRate) {
                throw InvalidCheckoutTransitionException::because('Selected shipping rate is not available for this address.');
            }

            $checkout->forceFill([
                'shipping_method_id' => $rate->getKey(),
                'status' => CheckoutStatus::ShippingSelected,
            ])->save();

            $this->pricing->calculate($checkout);

            return $checkout->refresh();
        });
    }

    public function selectPaymentMethod(Checkout $checkout, string $paymentMethod): Checkout
    {
        return DB::transaction(function () use ($checkout, $paymentMethod): Checkout {
            $checkout = $this->freshCheckout($checkout);

            if ($checkout->status === CheckoutStatus::PaymentSelected) {
                return $checkout;
            }

            $this->assertStatus($checkout, [CheckoutStatus::ShippingSelected]);

            if (! in_array($paymentMethod, ['credit_card', 'paypal', 'bank_transfer'], true)) {
                throw InvalidCheckoutTransitionException::because('Payment method is invalid.');
            }

            if ($checkout->totals_json === null) {
                $this->pricing->calculate($checkout);
            }

            CartLine::withoutGlobalScopes()
                ->where('cart_id', $checkout->cart_id)
                ->get()
                ->each(function (CartLine $line): void {
                    $inventory = InventoryItem::withoutGlobalScopes()
                        ->where('variant_id', $line->variant_id)
                        ->firstOrFail();

                    $this->inventory->reserve($inventory, $line->quantity);
                });

            $checkout->forceFill([
                'payment_method' => $paymentMethod,
                'status' => CheckoutStatus::PaymentSelected,
                'expires_at' => now()->addDay(),
            ])->save();

            return $checkout->refresh();
        });
    }

    public function expireCheckout(Checkout $checkout): Checkout
    {
        return DB::transaction(function () use ($checkout): Checkout {
            $checkout = $this->freshCheckout($checkout);

            if (in_array($checkout->status, [CheckoutStatus::Completed, CheckoutStatus::Expired], true)) {
                return $checkout;
            }

            if ($checkout->status === CheckoutStatus::PaymentSelected) {
                CartLine::withoutGlobalScopes()
                    ->where('cart_id', $checkout->cart_id)
                    ->get()
                    ->each(function (CartLine $line): void {
                        $inventory = InventoryItem::withoutGlobalScopes()
                            ->where('variant_id', $line->variant_id)
                            ->firstOrFail();

                        $this->inventory->release($inventory, $line->quantity);
                    });
            }

            $checkout->forceFill([
                'status' => CheckoutStatus::Expired,
            ])->save();

            return $checkout->refresh();
        });
    }

    /**
     * @param  array<string, mixed>  $paymentMethodData
     */
    public function completeCheckout(Checkout $checkout, array $paymentMethodData = []): Order
    {
        return $this->orders->createFromCheckout($checkout, $paymentMethodData);
    }

    private function freshCheckout(Checkout $checkout): Checkout
    {
        return Checkout::withoutGlobalScopes()
            ->with(['cart', 'store'])
            ->whereKey($checkout->getKey())
            ->lockForUpdate()
            ->firstOrFail();
    }

    /**
     * @param  array<int, CheckoutStatus>  $allowed
     */
    private function assertStatus(Checkout $checkout, array $allowed): void
    {
        if (! in_array($checkout->status, $allowed, true)) {
            throw InvalidCheckoutTransitionException::because("Checkout cannot transition from {$checkout->status->value}.");
        }
    }
}


sed -n '1,320p' app/Livewire/Admin/Products/Form.php

Form.php

<?php

namespace App\Livewire\Admin\Products;

use App\Actions\SanitizeHtml;
use App\Enums\MediaStatus;
use App\Enums\MediaType;
use App\Enums\ProductStatus;
use App\Enums\VariantStatus;
use App\Jobs\ProcessMediaUpload;
use App\Models\Collection;
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 App\Support\Money;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;
use Livewire\Component;
use Livewire\WithFileUploads;

class Form extends Component
{
    use WithFileUploads;

    public ?Product $product = null;

    public string $title = '';

    public string $descriptionHtml = '';

    public string $status = 'active';

    public string $vendor = '';

    public string $productType = '';

    public string $tags = '';

    public string $handle = '';

    public ?string $publishedAt = null;

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

    /**
     * @var array<int, array{name: string, values: string}>
     */
    public array $options = [];

    /**
     * @var array<int, array{id: int|null, label: string, sku: string, price: string, compareAtPrice: string, quantity: int, requiresShipping: bool, options: array<string, string>}>
     */
    public array $variants = [];

    /**
     * @var array<int, array{id: int, url: string, exists: bool, altText: string, position: int, status: string}>
     */
    public array $media = [];

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

    public function mount(?Product $product = null): void
    {
        if ($product?->exists) {
            $store = app('current_store');

            abort_unless($store instanceof Store && (int) $product->store_id === $store->getKey(), 404);

            $this->product = $product->load(['options.values', 'variants.inventoryItem', 'variants.optionValues.option', 'collections', 'media']);
            $this->fillFromProduct($this->product);

            return;
        }

        $this->variants = [[
            'id' => null,
            'label' => 'Default',
            'sku' => '',
            'price' => '0.00',
            'compareAtPrice' => '',
            'quantity' => 0,
            'requiresShipping' => true,
            'options' => [],
        ]];
    }

    public function updatedTitle(): void
    {
        if ($this->product === null && $this->handle === '') {
            $this->handle = Str::slug($this->title);
        }
    }

    public function addOption(): void
    {
        $this->options[] = [
            'name' => '',
            'values' => '',
        ];
    }

    public function removeOption(int $index): void
    {
        unset($this->options[$index]);
        $this->options = array_values($this->options);
    }

    public function generateVariants(): void
    {
        $optionPayload = $this->optionPayload();

        if ($optionPayload === []) {
            $template = $this->variants[0] ?? [];
            $this->variants = [[
                'id' => $template['id'] ?? null,
                'label' => 'Default',
                'sku' => $template['sku'] ?? '',
                'price' => $template['price'] ?? '0.00',
                'compareAtPrice' => $template['compareAtPrice'] ?? '',
                'quantity' => (int) ($template['quantity'] ?? 0),
                'requiresShipping' => (bool) ($template['requiresShipping'] ?? true),
                'options' => [],
            ]];

            return;
        }

        $existingVariants = collect($this->variants)
            ->keyBy(fn (array $variant): string => $this->variantOptionKey($variant['options'] ?? []));
        $template = $this->variants[0] ?? [];

        $this->variants = collect($this->optionCombinations($optionPayload))
            ->map(function (array $options) use ($existingVariants, $template): array {
                $existingVariant = $existingVariants->get($this->variantOptionKey($options));

                return [
                    'id' => $existingVariant['id'] ?? null,
                    'label' => $this->variantLabel($options),
                    'sku' => $existingVariant['sku'] ?? '',
                    'price' => $existingVariant['price'] ?? ($template['price'] ?? '0.00'),
                    'compareAtPrice' => $existingVariant['compareAtPrice'] ?? ($template['compareAtPrice'] ?? ''),
                    'quantity' => (int) ($existingVariant['quantity'] ?? 0),
                    'requiresShipping' => (bool) ($existingVariant['requiresShipping'] ?? ($template['requiresShipping'] ?? true)),
                    'options' => $options,
                ];
            })
            ->values()
            ->all();
    }

    public function save()…538 chars truncated…['nullable', 'string'],
            'handle' => [
                'required',
                'string',
                'max:255',
                Rule::unique('products', 'handle')
                    ->where('store_id', $store->getKey())
                    ->ignore($this->product?->getKey()),
            ],
            'variants' => ['required', 'array', 'min:1'],
            'variants.*.sku' => ['nullable', 'string', 'max:255'],
            'variants.*.price' => ['required', 'numeric', 'min:0'],
            'variants.*.compareAtPrice' => ['nullable', 'numeric', 'min:0'],
            'variants.*.quantity' => ['required', 'integer', 'min:0'],
            'variants.*.requiresShipping' => ['boolean'],
            'newMedia' => ['array', 'max:10'],
            'newMedia.*' => ['image', 'mimes:jpg,jpeg,png,gif,webp', 'max:5120'],
        ]);

        if (! $this->validateActiveVariantPricing() || ! $this->validateVariantSkus($store)) {
            return;
        }

        $product = DB::transaction(function () use ($store): Product {
            $productService = app(ProductService::class);

            if ($this->product === null) {
                $product = $productService->create($store, [
                    ...$this->productPayload(),
                    'options' => $this->optionPayload(),
                    'variants' => $this->variantPayload($store),
                ]);
            } else {
                $payload = $this->productPayload();
                $requestedStatus = ProductStatus::from((string) $payload['status']);
                unset($payload['status']);

                $product = $productService->update($this->product, $payload);
                $this->syncProductOptions($product);
                $this->syncExistingVariants($product, $store);

                if ($requestedStatus !== $product->refresh()->status) {
                    $productService->transitionStatus($product, $requestedStatus);
                }
            }

            $product->collections()->sync($this->collectionIds);

            return $product->refresh();
        });

        if ($this->newMedia !== []) {
            $this->storeNewMedia($product);
        }

        $this->product = $product->load(['options.values', 'variants.inventoryItem', 'variants.optionValues.option', 'collections', 'media']);
        $this->fillFromProduct($this->product);

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

    public function uploadMedia(): void
    {
        $product = $this->productForAction();

        $this->validate([
            'newMedia' => ['required', 'array', 'max:10'],
            'newMedia.*' => ['image', 'mimes:jpg,jpeg,png,gif,webp', 'max:5120'],
        ]);

        $this->storeNewMedia($product);

        $this->product = $product->refresh()->load(['options.values', 'variants.inventoryItem', 'variants.optionValues.option', 'collections', 'media']);
        $this->fillFromProduct($this->product);

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

    public function updateMediaAlt(int $mediaId): void
    {
        $index = $this->mediaIndex($mediaId);

        $this->validate([
            "media.{$index}.altText" => ['nullable', 'string', 'max:255'],
        ]);

        $media = $this->mediaRecord($mediaId);
        $altText = trim((string) $this->media[$index]['altText']);

        $media->forceFill([
            'alt_text' => $altText === '' ? null : $altText,
        ])->save();

        $this->refreshProductMedia();

        session()->flash('status', 'Media updated');
    }

    public function moveMedia(int $mediaId, string $direction): void
    {
        $ids = collect($this->media)->pluck('id')->map(fn (int $id): int => $id)->all();
        $index = array_search($mediaId, $ids, true);

        if ($index === false) {
            return;
        }

        $swapIndex = match ($direction) {
            'up' => $index - 1,
            'down' => $index + 1,
            default => $index,
        };

        if (! isset($ids[$swapIndex])) {
            return;
        }

        [$ids[$index], $ids[$swapIndex]] = [$ids[$swapIndex], $ids[$index]];

        $this->reorderMedia($ids);
    }

    /**
     * @param  array<int, int>  $order
     */
    public function reorderMedia(array $order): void
    {
        $product = $this->productForAction();
        $validIds = ProductMedia::withoutGlobalScopes()
            ->where('product_id', $product->getKey())
            ->whereIn('id', $order)
            ->pluck('id')
            ->all();

        $orderedIds = collect($order)
            ->map(fn (mixed $mediaId): int => (int) $mediaId)
            ->intersect($validIds)
            ->values();

        DB::transaction(function () use ($orderedIds): void {
            foreach ($orderedIds as $position => $mediaId) {


sed -n '1,360p' app/Services/OrderService.php

OrderService.php

<?php

namespace App\Services;

use App\Enums\CartStatus;
use App\Enums\CheckoutStatus;
use App\Enums\FinancialStatus;
use App\Enums\FulfillmentStatus;
use App\Enums\OrderStatus;
use App\Enums\PaymentMethod;
use App\Enums\PaymentStatus;
use App\Events\CheckoutCompleted;
use App\Events\OrderCancelled;
use App\Events\OrderCreated;
use App\Events\OrderPaid;
use App\Exceptions\InvalidCheckoutTransitionException;
use App\Exceptions\InvalidOrderOperationException;
use App\Exceptions\PaymentFailedException;
use App\Models\CartLine;
use App\Models\Checkout;
use App\Models\Discount;
use App\Models\InventoryItem;
use App\Models\Order;
use App\Models\OrderLine;
use App\Models\ProductOptionValue;
use App\Models\ProductVariant;
use App\Models\Store;
use App\Models\StoreSettings;
use Illuminate\Support\Collection;
use Illuminate\Support\Facades\DB;
use ValueError;

class OrderService
{
    public function __construct(
        private readonly PaymentService $payments,
        private readonly InventoryService $inventory,
        private readonly PricingEngine $pricing,
        private readonly FulfillmentService $fulfillments,
        private readonly DiscountService $discounts,
    ) {}

    /**
     * Create an order from a checkout after payment has been selected.
     *
     * @param  array<string, mixed>  $paymentMethodData
     */
    public function createFromCheckout(Checkout $checkout, array $paymentMethodData = []): Order
    {
        try {
            return DB::transaction(function () use ($checkout, $paymentMethodData): Order {
                $checkout = $this->freshCheckout($checkout);
                $existingOrder = Order::withoutGlobalScopes()
                    ->where('checkout_id', $checkout->getKey())
                    ->first();

                if ($existingOrder instanceof Order) {
                    return $existingOrder->load(['lines', 'payments', 'refunds', 'fulfillments.lines']);
                }

                if ($checkout->status !== CheckoutStatus::PaymentSelected) {
                    throw InvalidCheckoutTransitionException::because("Checkout cannot transition from {$checkout->status->value}.");
                }

                if ($checkout->totals_json === null) {
                    $this->pricing->calculate($checkout);
                    $checkout = $this->freshCheckout($checkout);
                }

                $method = $this->paymentMethod($checkout);
                $paymentResult = $this->payments->charge($checkout, $method, $paymentMethodData);

                if (! $paymentResult->success) {
                    throw PaymentFailedException::fromResult($paymentResult);
                }

                $paidImmediately = $paymentResult->status === PaymentStatus::Captured;
                $totals = $checkout->totals_json ?? [];

                $order = Order::withoutGlobalScopes()->create([
                    'store_id' => $checkout->store_id,
                    'checkout_id' => $checkout->getKey(),
                    'customer_id' => $checkout->customer_id,
                    'order_number' => $this->nextOrderNumber($checkout->store),
                    'payment_method' => $method,
                    'status' => $paidImmediately ? OrderStatus::Paid : OrderStatus::Pending,
                    'financial_status' => $paidImmediately ? FinancialStatus::Paid : FinancialStatus::Pending,
                    'fulfillment_status' => FulfillmentStatus::Unfulfilled,
                    'currency' => (string) data_get($totals, 'currency', $checkout->cart->currency),
                    'subtotal_amount' => (int) data_get($totals, 'subtotal', 0),
                    'discount_amount' => (int) data_get($totals, 'discount', 0),
                    'shipping_amount' => (int) data_get($totals, 'shipping', 0),
                    'tax_amount' => (int) data_get($totals, 'tax', 0),
                    'total_amount' => (int) data_get($totals, 'total', 0),
                    'email' => $checkout->email,
                    'billing_address_json' => $checkout->billing_address_json,
                    'shipping_address_json' => $checkout->shipping_address_json,
                    'placed_at' => now(),
                ]);

                $this->createOrderLines($checkout, $order, $this->discountAllocationsByCartLine($checkout));

                $order->payments()->create([
                    'provider' => 'mock',
                    'method' => $method,
                    'provider_payment_id' => $paymentResult->referenceId,
                    'status' => $paymentResult->status,
                    'amount' => $order->total_amount,
                    'currency' => $order->currency,
                    'raw_json_encrypted' => $paymentResult->toArray(),
                ]);

                if ($paidImmediately) {
                    $this->commitReservedInventory($checkout);
                }

                $checkout->cart->forceFill([
                    'status' =>…3464 chars truncated…           throw InvalidCheckoutTransitionException::because('Payment method is invalid.');
        }
    }

    private function nextOrderNumber(Store $store): string
    {
        $settings = StoreSettings::query()
            ->where('store_id', $store->getKey())
            ->first()
            ?->settings_json ?? [];
        $prefix = (string) data_get($settings, 'order_number_prefix', '#');
        $start = max(1, (int) data_get($settings, 'order_number_start', 1001));
        $maxExisting = Order::withoutGlobalScopes()
            ->where('store_id', $store->getKey())
            ->pluck('order_number')
            ->map(fn (string $orderNumber): ?int => $this->sequenceFromOrderNumber($orderNumber))
            ->filter()
            ->max();

        return $prefix.((int) max($start - 1, $maxExisting ?? 0) + 1);
    }

    private function sequenceFromOrderNumber(string $orderNumber): ?int
    {
        $digits = preg_replace('/\D+/', '', $orderNumber);

        return $digits === '' ? null : (int) $digits;
    }

    /**
     * @param  array<int, list<array{discount_id: int|null, code: string|null, amount: int}>>  $discountAllocations
     */
    private function createOrderLines(Checkout $checkout, Order $order, array $discountAllocations): void
    {
        $this->cartLines($checkout)->each(function (CartLine $line) use ($discountAllocations, $order): void {
            $variant = $line->variant;

            $order->lines()->create([
                'product_id' => $variant?->product_id,
                'variant_id' => $variant?->getKey(),
                'title_snapshot' => $this->titleSnapshot($variant),
                'sku_snapshot' => $variant?->sku,
                'quantity' => $line->quantity,
                'unit_price_amount' => $line->unit_price_amount,
                'total_amount' => $line->line_total_amount,
                'tax_lines_json' => [],
                'discount_allocations_json' => $discountAllocations[$line->getKey()] ?? [],
            ]);
        });
    }

    private function titleSnapshot(?ProductVariant $variant): string
    {
        $title = $variant?->product?->title ?? 'Product';
        $optionValues = $variant?->optionValues
            ->sortBy(fn (ProductOptionValue $value): int => $value->option?->position ?? $value->position)
            ->pluck('value')
            ->filter()
            ->implode(' / ');

        return $optionValues ? "{$title} - {$optionValues}" : $title;
    }

    /**
     * @return array<int, list<array{discount_id: int|null, code: string|null, amount: int}>>
     */
    private function discountAllocationsByCartLine(Checkout $checkout): array
    {
        $lines = $this->cartLines($checkout)
            ->map(function (CartLine $line): CartLine {
                $simulatedLine = clone $line;
                $simulatedLine->forceFill([
                    'line_discount_amount' => 0,
                    'line_total_amount' => $line->line_subtotal_amount,
                ]);

                return $simulatedLine;
            });
        $allocations = [];

        foreach ($this->appliedDiscounts($checkout) as $discount) {
            $result = $this->discounts->calculate($discount, $lines->sum('line_subtotal_amount'), $lines->all());

            foreach ($result->allocations as $lineId => $amount) {
                if ($amount <= 0) {
                    continue;
                }

                $allocations[(int) $lineId][] = [
                    'discount_id' => $discount->getKey(),
                    'code' => $discount->code,
                    'amount' => $amount,
                ];
            }

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

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

        return $allocations;
    }

    /**
     * @return Collection<int, Discount>
     */
    private function appliedDiscounts(Checkout $checkout): Collection
    {
        $discounts = collect();
        $code = trim((string) $checkout->discount_code);

        if ($code !== '') {
            $discount = Discount::withoutGlobalScopes()
                ->where('store_id', $checkout->store_id)
                ->whereRaw('lower(code) = ?', [mb_strtolower($code)])
                ->first();

            if ($discount instanceof Discount) {
                $discounts->push($discount);
            }
        }

        return $discounts
            ->merge($this->discounts->automaticForCart($checkout->store, $checkout->cart))
            ->values();
    }

    private function commitReservedInventory(Checkout $checkout): void
    {
        $this->cartLines($checkout)->each(function (CartLine $line): void {


sed -n '1,340p' app/Livewire/Admin/Collections/Form.php

Form.php

<?php

namespace App\Livewire\Admin\Collections;

use App\Models\Collection;
use App\Models\Product;
use App\Models\Store;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Collection as SupportCollection;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;
use Livewire\Component;

class Form extends Component
{
    public ?Collection $collection = null;

    public string $title = '';

    public string $handle = '';

    public string $descriptionHtml = '';

    public string $status = 'active';

    public string $productSearch = '';

    public string $actionMessage = '';

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

    public function mount(?Collection $collection = null): void
    {
        if ($collection?->exists) {
            $store = app('current_store');

            abort_unless($store instanceof Store && (int) $collection->store_id === $store->getKey(), 404);

            $this->collection = $collection->load('products');
            $this->fillFromCollection($this->collection);
        }
    }

    public function updatedTitle(): void
    {
        if ($this->collection === null && $this->handle === '') {
            $this->handle = Str::slug($this->title);
        }
    }

    public function addProduct(int $productId): void
    {
        if (! in_array($productId, $this->assignedProductIds, true)) {
            $this->assignedProductIds[] = $productId;
        }

        $this->productSearch = '';
    }

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

    public function save(): void
    {
        $store = app('current_store');
        abort_unless($store instanceof Store, 404);

        $this->validate([
            'title' => ['required', 'string', 'max:255'],
            'handle' => [
                'required',
                'string',
                'max:255',
                Rule::unique('collections', 'handle')
                    ->where('store_id', $store->getKey())
                    ->ignore($this->collection?->getKey()),
            ],
            'descriptionHtml' => ['nullable', 'string', 'max:65535'],
            'status' => ['required', Rule::in(['draft', 'active', 'archived'])],
        ]);

        $attributes = [
            'store_id' => $store->getKey(),
            'title' => $this->title,
            'handle' => Str::slug($this->handle),
            'description_html' => $this->descriptionHtml ?: null,
            'type' => 'manual',
            'status' => $this->status,
        ];

        $collection = $this->collection instanceof Collection
            ? tap($this->collection)->update($attributes)
            : Collection::query()->create($attributes);

        $collection->products()->sync(collect($this->assignedProductIds)
            ->values()
            ->mapWithKeys(fn (int $productId, int $position): array => [$productId => ['position' => $position]])
            ->all());

        $this->collection = $collection->refresh()->load('products');
        $this->fillFromCollection($this->collection);

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

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

        return Product::query()
            ->whereNotIn('id', $this->assignedProductIds)
            ->where(function (Builder $query): void {
                $query
                    ->where('title', 'like', '%'.$this->productSearch.'%')
                    ->orWhere('handle', 'like', '%'.$this->productSearch.'%');
            })
            ->limit(5)
            ->get();
    }

    public function assignedProducts(): SupportCollection
    {
        if ($this->assignedProductIds === []) {
            return collect();
        }

        return Product::query()
            ->whereIn('id', $this->assignedProductIds)
            ->get()
            ->sortBy(fn (Product $product): int => array_search($product->getKey(), $this->assignedProductIds, true))
            ->values();
    }

    public function render(): mixed
    {
        return view('livewire.admin.collections.form', [
            'searchResults' => $this->searchResults(),
            'assignedProducts' => $this->assignedProducts(),
            'isEditing' => $this->collection !== null,
        ])->layout('layouts.app', [
            'title' => $this->collection ? $this->collection->title : __('Add collection'),
        ]);
    }

    private function fillFromCollection(Collection $collection): void
    {
        $this->title = $collection->title;
        $this->handle = $collection->handle;
        $this->descriptionHtml = (string) $collection->description_html;
        $this->status = $collection->status->value;
        $this->assignedProductIds = $collection->products->pluck('id')->map(fn (int $id): int => $id)->all();
    }
}


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

namespace App\Livewire\Admin\Products;

use App\Actions\SanitizeHtml;
use App\Enums\MediaStatus;
use App\Enums\MediaType;
use App\Enums\ProductStatus;
use App\Enums\VariantStatus;
use App\Jobs\ProcessMediaUpload;
use App\Models\Collection;
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 App\Support\Money;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Schema;
use Illuminate\Support\Facades\Storage;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;
use Livewire\Component;
use Livewire\WithFileUploads;

class Form extends Component
{
    use WithFileUploads;

    public ?Product $product = null;

    public string $title = '';

    public string $descriptionHtml = '';

    public string $status = 'active';

    public string $vendor = '';

    public string $productType = '';

    public string $tags = '';

    public string $handle = '';

    public ?string $publishedAt = null;

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

    /**
     * @var array<int, array{name: string, values: string}>
     */
    public array $options = [];

    /**
     * @var array<int, array{id: int|null, label: string, sku: string, price: string, compareAtPrice: string, quantity: int, requiresShipping: bool, options: array<string, string>}>
     */
    public array $variants = [];

    /**
     * @var array<int, array{id: int, url: string, exists: bool, altText: string, position: int, status: string}>
     */
    public array $media = [];

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

    public function mount(?Product $product = null): void
    {
        if ($product?->exists) {
            $store = app('current_store');

            abort_unless($store instanceof Store && (int) $product->store_id === $store->getKey(), 404);

            $this->product = $product->load(['options.values', 'variants.inventoryItem', 'variants.optionValues.option', 'collections', 'media']);
            $this->fillFromProduct($this->product);

            return;
        }

        $this->variants = [[
            'id' => null,
            'label' => 'Default',
            'sku' => '',
            'price' => '0.00',
            'compareAtPrice' => '',
            'quantity' => 0,
            'requiresShipping' => true,
            'options' => [],
        ]];
    }

    public function updatedTitle(): void
    {
        if ($this->product === null && $this->handle === '') {
            $this->handle = Str::slug($this->title);
        }
    }

    public function addOption(): void
    {
        $this->options[] = [
            'name' => '',
            'values' => '',
        ];
    }

    public function removeOption(int $index): void
    {
        unset($this->options[$index]);
        $this->options = array_values($this->options);
    }

    public function generateVariants(): void
    {
        $optionPayload = $this->optionPayload();

        if ($optionPayload === []) {
            $template = $this->variants[0] ?? [];
            $this->variants = [[
                'id' => $template['id'] ?? null,
                'label' => 'Default',
                'sku' => $template['sku'] ?? '',
                'price' => $template['price'] ?? '0.00',
                'compareAtPrice' => $template['compareAtPrice'] ?? '',
                'quantity' => (int) ($template['quantity'] ?? 0),
                'requiresShipping' => (bool) ($template['requiresShipping'] ?? true),
                'options' => [],
            ]];

            return;
        }

        $existingVariants = collect($this->variants)
            ->keyBy(fn (array $variant): string => $this->variantOptionKey($variant['options'] ?? []));
        $template = $this->variants[0] ?? [];

        $this->variants = collect($this->optionCombinations($optionPayload))
            ->map(function (array $options) use ($existingVariants, $template): array {
                $existingVariant = $existingVariants->get($this->variantOptionKey($options));

                return [
                    'id' => $existingVariant['id'] ?? null,
                    'label' => $this->variantLabel($options),
                    'sku' => $existingVariant['sku'] ?? '',
                    'price' => $existingVariant['price'] ?? ($template['price'] ?? '0.00'),
                    'compareAtPrice' => $existingVariant['compareAtPrice'] ?? ($template['compareAtPrice'] ?? ''),
                    'quantity' => (int) ($existingVariant['quantity'] ?? 0),
                    'requiresShipping' => (bool) ($existingVariant['requiresShipping'] ?? ($template['requiresShipping'] ?? true)),
                    'options' => $options,
                ];
            })
            ->values()
            ->all();
    }

    public function save(): void
    {
        $store = app('current_store');
        abort_unless($store instanceof Store, 404);

        $this->ensureVariantMatrixMatchesOptions();

        $this->validate([
            'title' => ['required', 'string', 'max:255'],
            'descriptionHtml' => ['nullable', 'string', 'max:65535'],
            'status' => ['required', Rule::in(['draft', 'active', 'archived'])],
            'vendor' => ['nullable', 'string', 'max:255'],
            'productType' => ['nullable', 'string', 'max:255'],
            'tags' => ['nullable', 'string'],
            'handle' => [
                'required',
                'string',
                'max:255',
                Rule::unique('products', 'handle')
                    ->where('store_id', $store->getKey())
                    ->ignore($this->product?->getKey()),
            ],
            'variants' => ['required', 'array', 'min:1'],
            'variants.*.sku' => ['nullable', 'string', 'max:255'],
            'variants.*.price' => ['required', 'numeric', 'min:0'],
            'variants.*.compareAtPrice' => ['nullable', 'numeric', 'min:0'],
            'variants.*.quantity' => ['required', 'integer', 'min:0'],
            'variants.*.requiresShipping' => ['boolean'],
            'newMedia' => ['array', 'max:10'],
            'newMedia.*' => ['image', 'mimes:jpg,jpeg,png,gif,webp', 'max:5120'],
        ]);

        if (! $this->validateActiveVariantPricing() || ! $this->validateVariantSkus($store)) {
            return;
        }

        $product = DB::transaction(function () use ($store): Product {
            $productService = app(ProductService::class);

            if ($this->product === null) {
                $product = $productService->create($store, [
                    ...$this->productPayload(),
                    'options' => $this->optionPayload(),
                    'variants' => $this->variantPayload($store),
                ]);
            } else {
                $payload = $this->productPayload();
                $requestedStatus = ProductStatus::from((string) $payload['status']);
                unset($payload['status']);

                $product = $productService->update($this->product, $payload);
                $this->syncProductOptions($product);
                $this->syncExistingVariants($product, $store);

                if ($requestedStatus !== $product->refresh()->status) {
                    $productService->transitionStatus($product, $requestedStatus);
                }
            }

            $product->collections()->sync($this->collectionIds);

            return $product->refresh();
        });

        if ($this->newMedia !== []) {
            $this->storeNewMedia($product);
        }

        $this->product = $product->load(['options.values', 'variants.inventoryItem', 'variants.optionValues.option', 'collections', 'media']);
        $this->fillFromProduct($this->product);

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

    public function uploadMedia(): void
    {
        $product = $this->productForAction();

        $this->validate([
            'newMedia' => ['required', 'array', 'max:10'],
            'newMedia.*' => ['image', 'mimes:jpg,jpeg,png,gif,webp', 'max:5120'],
        ]);

        $this->storeNewMedia($product);

        $this->product = $product->refresh()->load(['options.values', 'variants.inventoryItem', 'variants.optionValues.option', 'collections', 'media']);
        $this->fillFromProduct($this->product);

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

    public function updateMediaAlt(int $mediaId): void
    {
        $index = $this->mediaIndex($mediaId);

        $this->validate([
            "media.{$index}.altText" => ['nullable', 'string', 'max:255'],
        ]);

        $media = $this->mediaRecord($mediaId);
        $altText = trim((string) $this->media[$index]['altText']);

        $media->forceFill([
            'alt_text' => $altText === '' ? null : $altText,
        ])->save();

        $this->refreshProductMedia();

        session()->flash('status', 'Media updated');
    }

    public function moveMedia(int $mediaId, string $direction): void
    {
        $ids = collect($this->media)->pluck('id')->map(fn (int $id): int => $id)->all();
        $index = array_search($mediaId, $ids, true);

        if ($index === false) {
            return;
        }

        $swapIndex = match ($direction) {
            'up' => $index - 1,
            'down' => $index + 1,
            default => $index,
        };

        if (! isset($ids[$swapIndex])) {
            return;
        }

        [$ids[$index], $ids[$swapIndex]] = [$ids[$swapIndex], $ids[$index]];

        $this->reorderMedia($ids);
    }

    /**
     * @param  array<int, int>  $order
     */
    public function reorderMedia(array $order): void
    {
        $product = $this->productForAction();
        $validIds = ProductMedia::withoutGlobalScopes()
            ->where('product_id', $product->getKey())
            ->whereIn('id', $order)
            ->pluck('id')
            ->all();

        $orderedIds = collect($order)
            ->map(fn (mixed $mediaId): int => (int) $mediaId)
            ->intersect($validIds)
            ->values();

        DB::transaction(function () use ($orderedIds): void {
            foreach ($orderedIds as $position => $mediaId) {


Output:
Chunk ID: 67a2c9
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 1315
Output:
<?php

namespace App\Livewire\Admin\Collections;

use App\Models\Collection;
use App\Models\Product;
use App\Models\Store;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Collection as SupportCollection;
use Illuminate\Support\Str;
use Illuminate\Validation\Rule;
use Livewire\Component;

class Form extends Component
{
    public ?Collection $collection = null;

    public string $title = '';

    public string $handle = '';

    public string $descriptionHtml = '';

    public string $status = 'active';

    public string $productSearch = '';

    public string $actionMessage = '';

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

    public function mount(?Collection $collection = null): void
    {
        if ($collection?->exists) {
            $store = app('current_store');

            abort_unless($store instanceof Store && (int) $collection->store_id === $store->getKey(), 404);

            $this->collection = $collection->load('products');
            $this->fillFromCollection($this->collection);
        }
    }

    public function updatedTitle(): void
    {
        if ($this->collection === null && $this->handle === '') {
            $this->handle = Str::slug($this->title);
        }
    }

    public function addProduct(int $productId): void
    {
        if (! in_array($productId, $this->assignedProductIds, true)) {
            $this->assignedProductIds[] = $productId;
        }

        $this->productSearch = '';
    }

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

    public function save(): void
    {
        $store = app('current_store');
        abort_unless($store instanceof Store, 404);

        $this->validate([
            'title' => ['required', 'string', 'max:255'],
            'handle' => [
                'required',
                'string',
                'max:255',
                Rule::unique('collections', 'handle')
                    ->where('store_id', $store->getKey())
                    ->ignore($this->collection?->getKey()),
            ],
            'descriptionHtml' => ['nullable', 'string', 'max:65535'],
            'status' => ['required', Rule::in(['draft', 'active', 'archived'])],
        ]);

        $attributes = [
            'store_id' => $store->getKey(),
            'title' => $this->title,
            'handle' => Str::slug($this->handle),
            'description_html' => $this->descriptionHtml ?: null,
            'type' => 'manual',
            'status' => $this->status,
        ];

        $collection = $this->collection instanceof Collection
            ? tap($this->collection)->update($attributes)
            : Collection::query()->create($attributes);

        $collection->products()->sync(collect($this->assignedProductIds)
            ->values()
            ->mapWithKeys(fn (int $productId, int $position): array => [$productId => ['position' => $position]])
            ->all());

        $this->collection = $collection->refresh()->load('products');
        $this->fillFromCollection($this->collection);

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

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

        return Product::query()
            ->whereNotIn('id', $this->assignedProductIds)
            ->where(function (Builder $query): void {
                $query
                    ->where('title', 'like', '%'.$this->productSearch.'%')
                    ->orWhere('handle', 'like', '%'.$this->productSearch.'%');
            })
            ->limit(5)
            ->get();
    }

    public function assignedProducts(): SupportCollection
    {
        if ($this->assignedProductIds === []) {
            return collect();
        }

        return Product::query()
            ->whereIn('id', $this->assignedProductIds)
            ->get()
            ->sortBy(fn (Product $product): int => array_search($product->getKey(), $this->assignedProductIds, true))
            ->values();
    }

    public function render(): mixed
    {
        return view('livewire.admin.collections.form', [
            'searchResults' => $this->searchResults(),
            'assignedProducts' => $this->assignedProducts(),
            'isEditing' => $this->collection !== null,
        ])->layout('layouts.app', [
            'title' => $this->collection ? $this->collection->title : __('Add collection'),
        ]);
    }

    private function fillFromCollection(Collection $collection): void
    {
        $this->title = $collection->title;
        $this->handle = $collection->handle;
        $this->descriptionHtml = (string) $collection->description_html;
        $this->status = $collection->status->value;
        $this->assignedProductIds = $collection->products->pluck('id')->map(fn (int $id): int => $id)->all();
    }
}