command: sed -n '1,240p' tests/Browser/Storefront/CheckoutTest.php

aggregated_output:
<?php

use Database\Seeders\DatabaseSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Pest\Browser\Playwright\Playwright;

uses(RefreshDatabase::class);

beforeEach(function (): void {
    Playwright::setHost('shop.test');

    $this->seed(DatabaseSeeder::class);
});

afterEach(function (): void {
    Playwright::setHost(null);
});

function storefrontCheckoutHost(): array
{
    return ['host' => 'shop.test'];
}

function storefrontCheckoutStart(): mixed
{
    return visit('/products/classic-cotton-t-shirt', storefrontCheckoutHost())
        ->click('M')
        ->wait(1)
        ->click('Black')
        ->wait(1)
        ->click('Add to cart')
        ->wait(1)
        ->navigate('/cart')
        ->wait(1)
        ->click('main button:has-text("Checkout")')
        ->wait(1)
        ->assertPathIs('/checkout')
        ->assertSee('Checkout');
}

/**
 * @param  array<string, string>  $overrides
 */
function storefrontCheckoutFillAddress(mixed $page, array $overrides = []): mixed
{
    $address = [
        'email' => 'test-buyer@example.com',
        'first_name' => 'Test',
        'last_name' => 'Buyer',
        'address1' => 'Teststrasse 1',
        'city' => 'Berlin',
        'postal_code' => '10115',
        'country' => 'DE',
    ];

    $address = array_replace($address, $overrides);

    return $page
        ->fill('input[wire\\:model="email"]', $address['email'])
        ->fill('input[wire\\:model="shippingAddress.first_name"]', $address['first_name'])
        ->fill('input[wire\\:model="shippingAddress.last_name"]', $address['last_name'])
        ->fill('input[wire\\:model="shippingAddress.address1"]', $address['address1'])
        ->fill('input[wire\\:model="shippingAddress.city"]', $address['city'])
        ->fill('input[wire\\:model="shippingAddress.postal_code"]', $address['postal_code'])
        ->select('select[wire\\:model="shippingAddress.country"]', $address['country']);
}

function storefrontCheckoutSubmitAddress(mixed $page): mixed
{
    return $page
        ->click('form[wire\\:submit="saveAddress"] button[type="submit"]')
        ->wait(1);
}

function storefrontCheckoutReachShipping(array $address = []): mixed
{
    return storefrontCheckoutSubmitAddress(
        storefrontCheckoutFillAddress(storefrontCheckoutStart(), $address),
    );
}

function storefrontCheckoutReachPayment(array $address = []): mixed
{
    return storefrontCheckoutReachShipping($address)
        ->click('button:has-text("Standard Shipping")')
        ->wait(1)
        ->click('button[wire\\:click="selectShippingMethod"]')
        ->wait(1)
        ->assertSee('Payment')
        ->assertSee('Pay now');
}

function storefrontCheckoutFillSuccessfulCard(mixed $page): mixed
{
    return $page
        ->fill('input[wire\\:model="cardNumber"]', '4242 4242 4242 4242')
        ->fill('input[wire\\:model="cardName"]', 'Test Buyer')
        ->fill('input[wire\\:model="cardExpiry"]', '12/28')
        ->fill('input[wire\\:model="cardCvc"]', '123');
}

function storefrontCheckoutApplyCartDiscount(string $code): mixed
{
    return visit('/products/classic-cotton-t-shirt', storefrontCheckoutHost())
        ->click('M')
        ->wait(1)
        ->click('Black')
        ->wait(1)
        ->click('Add to cart')
        ->wait(1)
        ->navigate('/cart')
        ->wait(1)
        ->fill('input[wire\\:model="discountCode"]', $code)
        ->click('button:has-text("Apply")')
        ->wait(1);
}

test('completes full checkout with credit card', function (): void {
    storefrontCheckoutFillSuccessfulCard(storefrontCheckoutReachPayment())
        ->assertSee('29.98')
        ->click('button:has-text("Pay now")')
        ->wait(2)
        ->assertPathBeginsWith('/checkout/confirmation')
        ->assertSee('Thank you')
        ->assertSee('#1001')
        ->assertNoJavaScriptErrors();
});

test('shows shipping methods based on german address', function (): void {
    storefrontCheckoutReachShipping([
        'email' => 'test@example.com',
        'first_name' => 'Hans',
        'last_name' => 'Mueller',
        'address1' => 'Berliner Str. 10',
        'city' => 'Munich',
        'postal_code' => '80331',
        'country' => 'DE',
    ])
        ->assertSee('Standard Shipping')
        ->assertSee('4.99')
        ->assertNoJavaScriptErrors();
});

test('shows international shipping methods for non german address', function (): void {
    storefrontCheckoutReachShipping([
        'email' => 'test@example.com',
        'first_name' => 'John',
        'last_name' => 'Smith',
        'address1' => '123 Main St',
        'city' => 'New York',
        'postal_code' => '10001',
        'country' => 'US',
    ])
        ->assertSee('International Shipping')
        ->assertSee('14.99')
        ->assertNoJavaScriptErrors();
});

test('applies discount during checkout', function (): void {
    $page = storefrontCheckoutApplyCartDiscount('FLAT5')
        ->assertSee('FLAT5')
        ->click('main button:has-text("Checkout")')
        ->wait(1)
        ->assertPathIs('/checkout');

    storefrontCheckoutSubmitAddress(storefrontCheckoutFillAddress($page))
        ->click('button:has-text("Standard Shipping")')
        ->wait(1)
        ->click('button[wire\\:click="selectShippingMethod"]')
        ->wait(1)
        ->assertSee('FLAT5')
        ->assertSee('5.00')
        ->assertSee('24.98')
        ->assertNoJavaScriptErrors();
});

test('validates required contact email', function (): void {
    storefrontCheckoutStart()
        ->click('form[wire\\:submit="saveAddress"] button[type="submit"]')
        ->wait(1)
        ->assertSee('email field is required')
        ->assertNoJavaScriptErrors();
});

test('validates required shipping address fields', function (): void {
    storefrontCheckoutStart()
        ->fill('input[wire\\:model="email"]', 'test@example.com')
        ->click('form[wire\\:submit="saveAddress"] button[type="submit"]')
        ->wait(1)
        ->assertSee('first name field is required')
        ->assertSee('last name field is required')
        ->assertSee('address1 field is required')
        ->assertSee('city field is required')
        ->assertSee('postal code field is required')
        ->assertNoJavaScriptErrors();
});

test('validates invalid postal code format', function (): void {
    storefrontCheckoutSubmitAddress(storefrontCheckoutFillAddress(storefrontCheckoutStart(), [
        'postal_code' => 'INVALID',
    ]))
        ->assertSee('postal code format is invalid')
        ->assertNoJavaScriptErrors();
});

test('prevents checkout with empty cart', function (): void {
    visit('/cart', storefrontCheckoutHost())
        ->assertSee('Your cart is empty')
        ->assertButtonDisabled('main button:has-text("Checkout")')
        ->assertNoJavaScriptErrors();
});

test('completes checkout with paypal', function (): void {
    storefrontCheckoutReachPayment()
        ->select('select[wire\\:model\\.live="paymentMethod"]', 'paypal')
        ->wait(1)
        ->assertSee('Pay with PayPal')
        ->click('button:has-text("Pay with PayPal")')
        ->wait(2)
        ->assertPathBeginsWith('/checkout/confirmation')
        ->assertSee('Thank you')
        ->assertSee('PayPal')
        ->assertNoJavaScriptErrors();
});

test('completes checkout with bank transfer', function (): void {
    storefrontCheckoutReachPayment()
        ->select('select[wire\\:model\\.live="paymentMethod"]', 'bank_transfer')
        ->wait(1)
        ->assertSee('bank transfer instructions')
        ->click('button:has-text("Place order")')
        ->wait(2)
        ->assertPathBeginsWith('/checkout/confirmation')
        ->assertSee('Thank you')
        ->assertSee('IBAN')
        ->assertSee('BIC')
        ->assertSee('Reference')
        ->assertSee('#1001')
        ->assertNoJavaScriptErrors();
});


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

use Database\Seeders\DatabaseSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Pest\Browser\Playwright\Playwright;

uses(RefreshDatabase::class);

beforeEach(function (): void {
    Playwright::setHost('shop.test');

    $this->seed(DatabaseSeeder::class);
});

afterEach(function (): void {
    Playwright::setHost(null);
});

function storefrontCheckoutHost(): array
{
    return ['host' => 'shop.test'];
}

function storefrontCheckoutStart(): mixed
{
    return visit('/products/classic-cotton-t-shirt', storefrontCheckoutHost())
        ->click('M')
        ->wait(1)
        ->click('Black')
        ->wait(1)
        ->click('Add to cart')
        ->wait(1)
        ->navigate('/cart')
        ->wait(1)
        ->click('main button:has-text("Checkout")')
        ->wait(1)
        ->assertPathIs('/checkout')
        ->assertSee('Checkout');
}

/**
 * @param  array<string, string>  $overrides
 */
function storefrontCheckoutFillAddress(mixed $page, array $overrides = []): mixed
{
    $address = [
        'email' => 'test-buyer@example.com',
        'first_name' => 'Test',
        'last_name' => 'Buyer',
        'address1' => 'Teststrasse 1',
        'city' => 'Berlin',
        'postal_code' => '10115',
        'country' => 'DE',
    ];

    $address = array_replace($address, $overrides);

    return $page
        ->fill('input[wire\\:model="email"]', $address['email'])
        ->fill('input[wire\\:model="shippingAddress.first_name"]', $address['first_name'])
        ->fill('input[wire\\:model="shippingAddress.last_name"]', $address['last_name'])
        ->fill('input[wire\\:model="shippingAddress.address1"]', $address['address1'])
        ->fill('input[wire\\:model="shippingAddress.city"]', $address['city'])
        ->fill('input[wire\\:model="shippingAddress.postal_code"]', $address['postal_code'])
        ->select('select[wire\\:model="shippingAddress.country"]', $address['country']);
}

function storefrontCheckoutSubmitAddress(mixed $page): mixed
{
    return $page
        ->click('form[wire\\:submit="saveAddress"] button[type="submit"]')
        ->wait(1);
}

function storefrontCheckoutReachShipping(array $address = []): mixed
{
    return storefrontCheckoutSubmitAddress(
        storefrontCheckoutFillAddress(storefrontCheckoutStart(), $address),
    );
}

function storefrontCheckoutReachPayment(array $address = []): mixed
{
    return storefrontCheckoutReachShipping($address)
        ->click('button:has-text("Standard Shipping")')
        ->wait(1)
        ->click('button[wire\\:click="selectShippingMethod"]')
        ->wait(1)
        ->assertSee('Payment')
        ->assertSee('Pay now');
}

function storefrontCheckoutFillSuccessfulCard(mixed $page): mixed
{
    return $page
        ->fill('input[wire\\:model="cardNumber"]', '4242 4242 4242 4242')
        ->fill('input[wire\\:model="cardName"]', 'Test Buyer')
        ->fill('input[wire\\:model="cardExpiry"]', '12/28')
        ->fill('input[wire\\:model="cardCvc"]', '123');
}

function storefrontCheckoutApplyCartDiscount(string $code): mixed
{
    return visit('/products/classic-cotton-t-shirt', storefrontCheckoutHost())
        ->click('M')
        ->wait(1)
        ->click('Black')
        ->wait(1)
        ->click('Add to cart')
        ->wait(1)
        ->navigate('/cart')
        ->wait(1)
        ->fill('input[wire\\:model="discountCode"]', $code)
        ->click('button:has-text("Apply")')
        ->wait(1);
}

test('completes full checkout with credit card', function (): void {
    storefrontCheckoutFillSuccessfulCard(storefrontCheckoutReachPayment())
        ->assertSee('29.98')
        ->click('button:has-text("Pay now")')
        ->wait(2)
        ->assertPathBeginsWith('/checkout/confirmation')
        ->assertSee('Thank you')
        ->assertSee('#1001')
        ->assertNoJavaScriptErrors();
});

test('shows shipping methods based on german address', function (): void {
    storefrontCheckoutReachShipping([
        'email' => 'test@example.com',
        'first_name' => 'Hans',
        'last_name' => 'Mueller',
        'address1' => 'Berliner Str. 10',
        'city' => 'Munich',
        'postal_code' => '80331',
        'country' => 'DE',
    ])
        ->assertSee('Standard Shipping')
        ->assertSee('4.99')
        ->assertNoJavaScriptErrors();
});

test('shows international shipping methods for non german address', function (): void {
    storefrontCheckoutReachShipping([
        'email' => 'test@example.com',
        'first_name' => 'John',
        'last_name' => 'Smith',
        'address1' => '123 Main St',
        'city' => 'New York',
        'postal_code' => '10001',
        'country' => 'US',
    ])
        ->assertSee('International Shipping')
        ->assertSee('14.99')
        ->assertNoJavaScriptErrors();
});

test('applies discount during checkout', function (): void {
    $page = storefrontCheckoutApplyCartDiscount('FLAT5')
        ->assertSee('FLAT5')
        ->click('main button:has-text("Checkout")')
        ->wait(1)
        ->assertPathIs('/checkout');

    storefrontCheckoutSubmitAddress(storefrontCheckoutFillAddress($page))
        ->click('button:has-text("Standard Shipping")')
        ->wait(1)
        ->click('button[wire\\:click="selectShippingMethod"]')
        ->wait(1)
        ->assertSee('FLAT5')
        ->assertSee('5.00')
        ->assertSee('24.98')
        ->assertNoJavaScriptErrors();
});

test('validates required contact email', function (): void {
    storefrontCheckoutStart()
        ->click('form[wire\\:submit="saveAddress"] button[type="submit"]')
        ->wait(1)
        ->assertSee('email field is required')
        ->assertNoJavaScriptErrors();
});

test('validates required shipping address fields', function (): void {
    storefrontCheckoutStart()
        ->fill('input[wire\\:model="email"]', 'test@example.com')
        ->click('form[wire\\:submit="saveAddress"] button[type="submit"]')
        ->wait(1)
        ->assertSee('first name field is required')
        ->assertSee('last name field is required')
        ->assertSee('address1 field is required')
        ->assertSee('city field is required')
        ->assertSee('postal code field is required')
        ->assertNoJavaScriptErrors();
});

test('validates invalid postal code format', function (): void {
    storefrontCheckoutSubmitAddress(storefrontCheckoutFillAddress(storefrontCheckoutStart(), [
        'postal_code' => 'INVALID',
    ]))
        ->assertSee('postal code format is invalid')
        ->assertNoJavaScriptErrors();
});

test('prevents checkout with empty cart', function (): void {
    visit('/cart', storefrontCheckoutHost())
        ->assertSee('Your cart is empty')
        ->assertButtonDisabled('main button:has-text("Checkout")')
        ->assertNoJavaScriptErrors();
});

test('completes checkout with paypal', function (): void {
    storefrontCheckoutReachPayment()
        ->select('select[wire\\:model\\.live="paymentMethod"]', 'paypal')
        ->wait(1)
        ->assertSee('Pay with PayPal')
        ->click('button:has-text("Pay with PayPal")')
        ->wait(2)
        ->assertPathBeginsWith('/checkout/confirmation')
        ->assertSee('Thank you')
        ->assertSee('PayPal')
        ->assertNoJavaScriptErrors();
});

test('completes checkout with bank transfer', function (): void {
    storefrontCheckoutReachPayment()
        ->select('select[wire\\:model\\.live="paymentMethod"]', 'bank_transfer')
        ->wait(1)
        ->assertSee('bank transfer instructions')
        ->click('button:has-text("Place order")')
        ->wait(2)
        ->assertPathBeginsWith('/checkout/confirmation')
        ->assertSee('Thank you')
        ->assertSee('IBAN')
        ->assertSee('BIC')
        ->assertSee('Reference')
        ->assertSee('#1001')
        ->assertNoJavaScriptErrors();
});


cmd: rg -n "order_number|next.*order|order_number_start|completeCheckout" app/Services app -S


cmd: sed -n '1,320p' app/Services/CheckoutService.php


cmd: sed -n '1,280p' app/Services/OrderService.php


command: sed -n '1,320p' app/Services/CheckoutService.php

CheckoutService.php

type: read

aggregated_output:
<?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}.");
        }
    }
}

status: completed


command: sed -n '1,280p' app/Services/OrderService.php

aggregated_output:
<?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\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' => CartStatus::Converted,
          …692 chars truncated…    } catch (PaymentFailedException $exception) {
            $this->releaseFailedPaymentReservation($checkout);

            throw $exception;
        }
    }

    public function confirmBankTransferPayment(Order $order): Order
    {
        return DB::transaction(function () use ($order): Order {
            $order = $this->freshOrder($order);
            $this->assertPendingBankTransfer($order);

            $order->payments()
                ->where('status', PaymentStatus::Pending->value)
                ->update(['status' => PaymentStatus::Captured->value]);

            $this->commitReservedOrderInventory($order);

            $order->forceFill([
                'status' => OrderStatus::Paid,
                'financial_status' => FinancialStatus::Paid,
            ])->save();

            $this->fulfillments->autoFulfillDigital($order);

            $order = $order->refresh()->load(['lines', 'payments', 'refunds', 'fulfillments.lines']);

            event(new OrderPaid($order));

            return $order;
        });
    }

    public function cancelUnpaidBankTransferOrder(Order $order): Order
    {
        return DB::transaction(function () use ($order): Order {
            $order = $this->freshOrder($order);
            $this->assertPendingBankTransfer($order);

            $this->releaseReservedOrderInventory($order);

            $order->payments()
                ->where('status', PaymentStatus::Pending->value)
                ->update(['status' => PaymentStatus::Failed->value]);

            $order->forceFill([
                'status' => OrderStatus::Cancelled,
                'financial_status' => FinancialStatus::Voided,
            ])->save();

            $order = $order->refresh()->load(['lines', 'payments', 'refunds', 'fulfillments.lines']);

            event(new OrderCancelled($order));

            return $order;
        });
    }

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

    private function freshOrder(Order $order): Order
    {
        return Order::withoutGlobalScopes()
            ->with(['lines', 'payments', 'store.settings'])
            ->whereKey($order->getKey())
            ->lockForUpdate()
            ->firstOrFail();
    }

    private function paymentMethod(Checkout $checkout): PaymentMethod
    {
        try {
            return PaymentMethod::from((string) $checkout->payment_method);
        } catch (ValueError) {
            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()


command: rg -n "order_number|next.*order|order_number_start|completeCheckout" app/Services app -S

type: search

cmd: rg -n 'order_number|next.*order|order_number_start|completeCheckout' app/Services app -S

query: order_number|next.*order|order_number_start|completeCheckout

path: Services

aggregated_output:
app/Services/CheckoutService.php:199:    public function completeCheckout(Checkout $checkout, array $paymentMethodData = []): Order
app/Services/CheckoutService.php:199:    public function completeCheckout(Checkout $checkout, array $paymentMethodData = []): Order
app/Services/OrderExportService.php:70:            'order_number',
app/Services/OrderExportService.php:94:                    $order->order_number,
app/Services/OrderExportService.php:137:                        ->where('order_number', 'like', $like)
app/Services/OrderExportService.php:70:            'order_number',
app/Services/OrderExportService.php:94:                    $order->order_number,
app/Services/OrderExportService.php:137:                        ->where('order_number', 'like', $like)
app/Support/OrderAccessToken.php:30:            $order->order_number,
app/Http/Resources/Admin/V1/CustomerResource.php:33:                'order_number' => $order->order_number,
app/Services/OrderService.php:83:                    'order_number' => $this->nextOrderNumber($checkout->store),
app/Services/OrderService.php:233:        $prefix = (string) data_get($settings, 'order_number_prefix', '#');
app/Services/OrderService.php:234:        $start = max(1, (int) data_get($settings, 'order_number_start', 1001));
app/Services/OrderService.php:237:            ->pluck('order_number')
app/Services/OrderService.php:83:                    'order_number' => $this->nextOrderNumber($checkout->store),
app/Services/OrderService.php:233:        $prefix = (string) data_get($settings, 'order_number_prefix', '#');
app/Services/OrderService.php:234:        $start = max(1, (int) data_get($settings, 'order_number_start', 1001));
app/Services/OrderService.php:237:            ->pluck('order_number')
app/Http/Resources/Admin/V1/OrderResource.php:20:            'order_number' => $this->order_number,
app/Listeners/DispatchWebhooks.php:97:                'order_number' => $order->order_number,
app/Livewire/Admin/Orders/Show.php:184:            'title' => $order->order_number,
app/Livewire/Admin/Orders/Index.php:90:                        ->where('order_number', 'like', $search)
app/Http/Controllers/Api/Admin/V1/OrderController.php:40:                        ->where('order_number', 'like', $like)
app/Http/Resources/Storefront/V1/OrderResource.php:21:            'order_number' => $this->order_number,
app/Http/Resources/Storefront/V1/OrderResource.php:65:                'reference' => $this->order_number,
app/Http/Controllers/Api/Storefront/V1/OrderController.php:23:            ->where('order_number', urldecode($orderNumber))
app/Http/Controllers/Api/Storefront/V1/CheckoutController.php:129:            $order = $checkouts->completeCheckout($checkout, [
app/Livewire/Storefront/Checkout/Show.php:240:            $order = app(CheckoutService::class)->completeCheckout($checkout, [
app/Models/Order.php:27:        'order_number',


output:
Chunk ID: d09762
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 725
Output:
app/Services/CheckoutService.php:199:    public function completeCheckout(Checkout $checkout, array $paymentMethodData = []): Order
app/Services/CheckoutService.php:199:    public function completeCheckout(Checkout $checkout, array $paymentMethodData = []): Order
app/Services/OrderExportService.php:70:            'order_number',
app/Services/OrderExportService.php:94:                    $order->order_number,
app/Services/OrderExportService.php:137:                        ->where('order_number', 'like', $like)
app/Services/OrderExportService.php:70:            'order_number',
app/Services/OrderExportService.php:94:                    $order->order_number,
app/Services/OrderExportService.php:137:                        ->where('order_number', 'like', $like)
app/Support/OrderAccessToken.php:30:            $order->order_number,
app/Http/Resources/Admin/V1/CustomerResource.php:33:                'order_number' => $order->order_number,
app/Services/OrderService.php:83:                    'order_number' => $this->nextOrderNumber($checkout->store),
app/Services/OrderService.php:233:        $prefix = (string) data_get($settings, 'order_number_prefix', '#');
app/Services/OrderService.php:234:        $start = max(1, (int) data_get($settings, 'order_number_start', 1001));
app/Services/OrderService.php:237:            ->pluck('order_number')
app/Services/OrderService.php:83:                    'order_number' => $this->nextOrderNumber($checkout->store),
app/Services/OrderService.php:233:        $prefix = (string) data_get($settings, 'order_number_prefix', '#');
app/Services/OrderService.php:234:        $start = max(1, (int) data_get($settings, 'order_number_start', 1001));
app/Services/OrderService.php:237:            ->pluck('order_number')
app/Http/Resources/Admin/V1/OrderResource.php:20:            'order_number' => $this->order_number,
app/Listeners/DispatchWebhooks.php:97:                'order_number' => $order->order_number,
app/Livewire/Admin/Orders/Show.php:184:            'title' => $order->order_number,
app/Livewire/Admin/Orders/Index.php:90:                        ->where('order_number', 'like', $search)
app/Http/Controllers/Api/Admin/V1/OrderController.php:40:                        ->where('order_number', 'like', $like)
app/Http/Resources/Storefront/V1/OrderResource.php:21:            'order_number' => $this->order_number,
app/Http/Resources/Storefront/V1/OrderResource.php:65:                'reference' => $this->order_number,
app/Http/Controllers/Api/Storefront/V1/OrderController.php:23:            ->where('order_number', urldecode($orderNumber))
app/Http/Controllers/Api/Storefront/V1/CheckoutController.php:129:            $order = $checkouts->completeCheckout($checkout, [
app/Livewire/Storefront/Checkout/Show.php:240:            $order = app(CheckoutService::class)->completeCheckout($checkout, [
app/Models/Order.php:27:        'order_number',


output:
Chunk ID: d45ec8
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 2057
Output:
<?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}.");
        }
    }
}


output:
Chunk ID: 6e6bcc
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 2673
Output:
<?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\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' => CartStatus::Converted,
                ])->save();

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

                $this->incrementDiscountUsage($checkout);

                if ($paidImmediately) {
                    $this->fulfillments->autoFulfillDigital($order);
                }

                $order = $order->refresh()->load(['lines', 'payments', 'refunds', 'fulfillments.lines']);

                event(new OrderCreated($order));

                if ($paidImmediately) {
                    event(new OrderPaid($order));
                }

                return $order;
            });
        } catch (PaymentFailedException $exception) {
            $this->releaseFailedPaymentReservation($checkout);

            throw $exception;
        }
    }

    public function confirmBankTransferPayment(Order $order): Order
    {
        return DB::transaction(function () use ($order): Order {
            $order = $this->freshOrder($order);
            $this->assertPendingBankTransfer($order);

            $order->payments()
                ->where('status', PaymentStatus::Pending->value)
                ->update(['status' => PaymentStatus::Captured->value]);

            $this->commitReservedOrderInventory($order);

            $order->forceFill([
                'status' => OrderStatus::Paid,
                'financial_status' => FinancialStatus::Paid,
            ])->save();

            $this->fulfillments->autoFulfillDigital($order);

            $order = $order->refresh()->load(['lines', 'payments', 'refunds', 'fulfillments.lines']);

            event(new OrderPaid($order));

            return $order;
        });
    }

    public function cancelUnpaidBankTransferOrder(Order $order): Order
    {
        return DB::transaction(function () use ($order): Order {
            $order = $this->freshOrder($order);
            $this->assertPendingBankTransfer($order);

            $this->releaseReservedOrderInventory($order);

            $order->payments()
                ->where('status', PaymentStatus::Pending->value)
                ->update(['status' => PaymentStatus::Failed->value]);

            $order->forceFill([
                'status' => OrderStatus::Cancelled,
                'financial_status' => FinancialStatus::Voided,
            ])->save();

            $order = $order->refresh()->load(['lines', 'payments', 'refunds', 'fulfillments.lines']);

            event(new OrderCancelled($order));

            return $order;
        });
    }

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

    private function freshOrder(Order $order): Order
    {
        return Order::withoutGlobalScopes()
            ->with(['lines', 'payments', 'store.settings'])
            ->whereKey($order->getKey())
            ->lockForUpdate()
            ->firstOrFail();
    }

    private function paymentMethod(Checkout $checkout): PaymentMethod
    {
        try {
            return PaymentMethod::from((string) $checkout->payment_method);
        } catch (ValueError) {
            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()


cmd: sed -n '280,520p' app/Services/OrderService.php


command: sed -n '280,520p' app/Services/OrderService.php

aggregated_output:
            ->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 {
            $this->inventory->commit($this->inventoryItemForVariant($line->variant_id), $line->quantity);
        });
    }

    private function commitReservedOrderInventory(Order $order): void
    {
        $order->lines->each(function (OrderLine $line): void {
            if ($line->variant_id !== null) {
                $this->inventory->commit($this->inventoryItemForVariant($line->variant_id), $line->quantity);
            }
        });
    }

    private function releaseReservedOrderInventory(Order $order): void
    {
        $order->lines->each(function (OrderLine $line): void {
            if ($line->variant_id !== null) {
                $this->inventory->release($this->inventoryItemForVariant($line->variant_id), $line->quantity);
            }
        });
    }

    private function releaseFailedPaymentReservation(Checkout $checkout): void
    {
        DB::transaction(function () use ($checkout): void {
            $checkout = $this->freshCheckout($checkout);

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

            $this->cartLines($checkout)->each(function (CartLine $line): void {
                $this->inventory->release($this->inventoryItemForVariant($line->variant_id), $line->quantity);
            });

            $checkout->forceFill([
                'status' => CheckoutStatus::ShippingSelected,
                'payment_method' => null,
                'expires_at' => null,
            ])->save();
        });
    }

    private function incrementDiscountUsage(Checkout $checkout): void
    {
        $code = trim((string) $checkout->discount_code);

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

        Discount::withoutGlobalScopes()
            ->where('store_id', $checkout->store_id)
            ->whereRaw('lower(code) = ?', [mb_strtolower($code)])
            ->increment('usage_count');
    }

    private function assertPendingBankTransfer(Order $order): void
    {
        if ($order->payment_method !== PaymentMethod::BankTransfer || $order->financial_status !== FinancialStatus::Pending) {
            throw InvalidOrderOperationException::because('Order is not a pending bank transfer order.');
        }
    }

    private function inventoryItemForVariant(int $variantId): InventoryItem
    {
        return InventoryItem::withoutGlobalScopes()
            ->where('variant_id', $variantId)
            ->firstOrFail();
    }

    /**
     * @return Collection<int, CartLine>
     */
    private function cartLines(Checkout $checkout): Collection
    {
        return CartLine::withoutGlobalScopes()
            ->with([
                'variant' => fn ($query) => $query->withoutGlobalScopes(),
                'variant.product' => fn ($query) => $query->withoutGlobalScopes(),
                'variant.optionValues' => fn ($query) => $query->withoutGlobalScopes(),
                'variant.optionValues.option' => fn ($query) => $query->withoutGlobalScopes(),
            ])
            ->where('cart_id', $checkout->cart_id)
            ->orderBy('id')
            ->get();
    }
}


output:
Chunk ID: fb504f
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 1442
Output:
            ->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 {
            $this->inventory->commit($this->inventoryItemForVariant($line->variant_id), $line->quantity);
        });
    }

    private function commitReservedOrderInventory(Order $order): void
    {
        $order->lines->each(function (OrderLine $line): void {
            if ($line->variant_id !== null) {
                $this->inventory->commit($this->inventoryItemForVariant($line->variant_id), $line->quantity);
            }
        });
    }

    private function releaseReservedOrderInventory(Order $order): void
    {
        $order->lines->each(function (OrderLine $line): void {
            if ($line->variant_id !== null) {
                $this->inventory->release($this->inventoryItemForVariant($line->variant_id), $line->quantity);
            }
        });
    }

    private function releaseFailedPaymentReservation(Checkout $checkout): void
    {
        DB::transaction(function () use ($checkout): void {
            $checkout = $this->freshCheckout($checkout);

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

            $this->cartLines($checkout)->each(function (CartLine $line): void {
                $this->inventory->release($this->inventoryItemForVariant($line->variant_id), $line->quantity);
            });

            $checkout->forceFill([
                'status' => CheckoutStatus::ShippingSelected,
                'payment_method' => null,
                'expires_at' => null,
            ])->save();
        });
    }

    private function incrementDiscountUsage(Checkout $checkout): void
    {
        $code = trim((string) $checkout->discount_code);

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

        Discount::withoutGlobalScopes()
            ->where('store_id', $checkout->store_id)
            ->whereRaw('lower(code) = ?', [mb_strtolower($code)])
            ->increment('usage_count');
    }

    private function assertPendingBankTransfer(Order $order): void
    {
        if ($order->payment_method !== PaymentMethod::BankTransfer || $order->financial_status !== FinancialStatus::Pending) {
            throw InvalidOrderOperationException::because('Order is not a pending bank transfer order.');
        }
    }

    private function inventoryItemForVariant(int $variantId): InventoryItem
    {
        return InventoryItem::withoutGlobalScopes()
            ->where('variant_id', $variantId)
            ->firstOrFail();
    }

    /**
     * @return Collection<int, CartLine>
     */
    private function cartLines(Checkout $checkout): Collection
    {
        return CartLine::withoutGlobalScopes()
            ->with([
                'variant' => fn ($query) => $query->withoutGlobalScopes(),
                'variant.product' => fn ($query) => $query->withoutGlobalScopes(),
                'variant.optionValues' => fn ($query) => $query->withoutGlobalScopes(),
                'variant.optionValues.option' => fn ($query) => $query->withoutGlobalScopes(),
            ])
            ->where('cart_id', $checkout->cart_id)
            ->orderBy('id')
            ->get();
    }
}


cmd: sed -n '1,220p' app/Services/InventoryService.php


command: sed -n '1,220p' app/Services/InventoryService.php

aggregated_output:
<?php

namespace App\Services;

use App\Enums\InventoryPolicy;
use App\Exceptions\InsufficientInventoryException;
use App\Models\InventoryItem;
use Illuminate\Support\Facades\DB;
use InvalidArgumentException;

class InventoryService
{
    public function checkAvailability(InventoryItem $item, int $quantity): bool
    {
        $this->assertPositiveQuantity($quantity);

        if ($item->policy === InventoryPolicy::Continue) {
            return true;
        }

        return $this->available($item) >= $quantity;
    }

    public function reserve(InventoryItem $item, int $quantity): void
    {
        $this->assertPositiveQuantity($quantity);

        DB::transaction(function () use ($item, $quantity): void {
            $locked = $this->freshItem($item);

            if (! $this->checkAvailability($locked, $quantity)) {
                throw InsufficientInventoryException::forQuantity($this->available($locked), $quantity);
            }

            $locked->forceFill([
                'quantity_reserved' => $locked->quantity_reserved + $quantity,
            ])->save();
        });
    }

    public function release(InventoryItem $item, int $quantity): void
    {
        $this->assertPositiveQuantity($quantity);

        DB::transaction(function () use ($item, $quantity): void {
            $locked = $this->freshItem($item);

            if ($locked->quantity_reserved < $quantity) {
                throw new InvalidArgumentException('Cannot release more inventory than is reserved.');
            }

            $locked->forceFill([
                'quantity_reserved' => $locked->quantity_reserved - $quantity,
            ])->save();
        });
    }

    public function commit(InventoryItem $item, int $quantity): void
    {
        $this->assertPositiveQuantity($quantity);

        DB::transaction(function () use ($item, $quantity): void {
            $locked = $this->freshItem($item);

            if ($locked->quantity_reserved < $quantity) {
                throw new InvalidArgumentException('Cannot commit more inventory than is reserved.');
            }

            $locked->forceFill([
                'quantity_on_hand' => $locked->quantity_on_hand - $quantity,
                'quantity_reserved' => $locked->quantity_reserved - $quantity,
            ])->save();
        });
    }

    public function restock(InventoryItem $item, int $quantity): void
    {
        $this->assertPositiveQuantity($quantity);

        DB::transaction(function () use ($item, $quantity): void {
            $locked = $this->freshItem($item);

            $locked->forceFill([
                'quantity_on_hand' => $locked->quantity_on_hand + $quantity,
            ])->save();
        });
    }

    private function available(InventoryItem $item): int
    {
        return $item->quantity_on_hand - $item->quantity_reserved;
    }

    private function freshItem(InventoryItem $item): InventoryItem
    {
        return InventoryItem::withoutGlobalScopes()
            ->whereKey($item->getKey())
            ->lockForUpdate()
            ->firstOrFail();
    }

    private function assertPositiveQuantity(int $quantity): void
    {
        if ($quantity <= 0) {
            throw new InvalidArgumentException('Inventory quantity must be greater than zero.');
        }
    }
}


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

namespace App\Services;

use App\Enums\InventoryPolicy;
use App\Exceptions\InsufficientInventoryException;
use App\Models\InventoryItem;
use Illuminate\Support\Facades\DB;
use InvalidArgumentException;

class InventoryService
{
    public function checkAvailability(InventoryItem $item, int $quantity): bool
    {
        $this->assertPositiveQuantity($quantity);

        if ($item->policy === InventoryPolicy::Continue) {
            return true;
        }

        return $this->available($item) >= $quantity;
    }

    public function reserve(InventoryItem $item, int $quantity): void
    {
        $this->assertPositiveQuantity($quantity);

        DB::transaction(function () use ($item, $quantity): void {
            $locked = $this->freshItem($item);

            if (! $this->checkAvailability($locked, $quantity)) {
                throw InsufficientInventoryException::forQuantity($this->available($locked), $quantity);
            }

            $locked->forceFill([
                'quantity_reserved' => $locked->quantity_reserved + $quantity,
            ])->save();
        });
    }

    public function release(InventoryItem $item, int $quantity): void
    {
        $this->assertPositiveQuantity($quantity);

        DB::transaction(function () use ($item, $quantity): void {
            $locked = $this->freshItem($item);

            if ($locked->quantity_reserved < $quantity) {
                throw new InvalidArgumentException('Cannot release more inventory than is reserved.');
            }

            $locked->forceFill([
                'quantity_reserved' => $locked->quantity_reserved - $quantity,
            ])->save();
        });
    }

    public function commit(InventoryItem $item, int $quantity): void
    {
        $this->assertPositiveQuantity($quantity);

        DB::transaction(function () use ($item, $quantity): void {
            $locked = $this->freshItem($item);

            if ($locked->quantity_reserved < $quantity) {
                throw new InvalidArgumentException('Cannot commit more inventory than is reserved.');
            }

            $locked->forceFill([
                'quantity_on_hand' => $locked->quantity_on_hand - $quantity,
                'quantity_reserved' => $locked->quantity_reserved - $quantity,
            ])->save();
        });
    }

    public function restock(InventoryItem $item, int $quantity): void
    {
        $this->assertPositiveQuantity($quantity);

        DB::transaction(function () use ($item, $quantity): void {
            $locked = $this->freshItem($item);

            $locked->forceFill([
                'quantity_on_hand' => $locked->quantity_on_hand + $quantity,
            ])->save();
        });
    }

    private function available(InventoryItem $item): int
    {
        return $item->quantity_on_hand - $item->quantity_reserved;
    }

    private function freshItem(InventoryItem $item): InventoryItem
    {
        return InventoryItem::withoutGlobalScopes()
            ->whereKey($item->getKey())
            ->lockForUpdate()
            ->firstOrFail();
    }

    private function assertPositiveQuantity(int $quantity): void
    {
        if ($quantity <= 0) {
            throw new InvalidArgumentException('Inventory quantity must be greater than zero.');
        }
    }
}


cmd: rg -n "title_snapshot|sku_snapshot|discount_allocations_json|tax_lines_json" resources/views/livewire/admin/orders resources/views/livewire/storefront/account/orders resources/views/livewire/storefront/checkout -S


cmd: sed -n '1,280p' resources/views/livewire/admin/orders/show.blade.php


cmd: sed -n '1,220p' resources/views/livewire/storefront/account/orders/show.blade.php


command: sed -n '1,280p' resources/views/livewire/admin/orders/show.blade.php

aggregated_output:
            <flux:button :href="route('admin.orders.index')" wire:navigate variant="ghost" icon="arrow-left">
                Orders
            </flux:button>

                <flux:heading size="xl">{{ $order->order_number }}</flux:heading>
                <flux:text class="mt-1">{{ $order->email }} · {{ $order->placed_at?->format('M j, Y H:i') }}</flux:text>

            @if ($order->payment_method === \App\Enums\PaymentMethod::BankTransfer && $order->financial_status === \App\Enums\FinancialStatus::Pending)
                <flux:button wire:click="confirmBankTransferPayment" variant="primary" icon="banknotes" data-test="confirm-payment-button">
                    Confirm payment
                </flux:button>
            @endif

            @if (in_array($order->financial_status, [\App\Enums\FinancialStatus::Paid, \App\Enums\FinancialStatus::PartiallyRefunded], true) && $refundableAmount > 0)
                <flux:modal.trigger name="refund-order">
                    <flux:button variant="danger" icon="receipt-refund" data-test="refund-modal-button">
                        Refund
                    </flux:button>
                </flux:modal.trigger>
            @endif

            @if (in_array($order->financial_status, [\App\Enums\FinancialStatus::Paid, \App\Enums\FinancialStatus::PartiallyRefunded], true) && collect($remainingFulfillmentQuantities)->sum() > 0)
                <flux:modal.trigger name="fulfillment-order">
                    <flux:button variant="filled" icon="truck" data-test="fulfillment-modal-button">
                        Create fulfillment
                    </flux:button>
                </flux:modal.trigger>
            @endif

    @if ($actionMessage !== '')
        <flux:callout color="green" icon="check-circle" data-test="order-action-message">{{ $actionMessage }}</flux:callout>
    @endif

    @error('orderAction')

            {{ $message }}

    @enderror

    @error('fulfillment')

            {{ $message }}

    @enderror

    @if (! in_array($order->financial_status, [\App\Enums\FinancialStatus::Paid, \App\Enums\FinancialStatus::PartiallyRefunded], true) && collect($remainingFulfillmentQuantities)->sum() > 0)
        <flux:callout color="amber" icon="exclamation-triangle" data-test="fulfillment-guard-message">
            Cannot create fulfillment. Payment must be confirmed before items can be fulfilled. Current financial status: {{ Str::headline($order->financial_status->value) }}.
        </flux:callout>
    @endif

Order

                <flux:badge>{{ Str::headline($order->status->value) }}</flux:badge>

Payment

                <flux:badge :color="$order->financial_status->value === 'paid' ? 'green' : ($order->financial_status->value === 'pending' ? 'amber' : 'zinc')">
                    {{ Str::headline($order->financial_status->value) }}
                </flux:badge>

Fulfillment

                <flux:badge :color="$order->fulfillment_status->value === 'fulfilled' ? 'green' : ($order->fulfillment_status->value === 'partial' ? 'amber' : 'zinc')">
                    {{ Str::headline($order->fulfillment_status->value) }}
                </flux:badge>

Total

                {{ \App\Support\Money::format($order->total_amount, $order->currency) }}

            lines as $line)

getKey() }}">
                                        {{ $line->orderLine?->title_snapshot }} · Qty {{ $line->quantity }}

                                @endforeach

                    @empty

No fulfillments yet.

                    @endforelse

                <flux:heading size="lg">Customer</flux:heading>

{{ $order->customer?->name ?: 'Guest checkout' }}

{{ $order->email }}

                @if ($order->customer)
                    <flux:button :href="route('admin.customers.show', $order->customer)" wire:navigate variant="filled" size="sm" class="mt-4">
                        View customer
                    </flux:button>
                @endif

                <flux:heading size="lg">Summary</flux:heading>

                        Subtotal
                        {{ \App\Support\Money::format($order->subtotal_amount, $order->currency) }}

                        Discount
                        -{{ \App\Support\Money::format($order->discount_amount, $order->currency) }}

                        Shipping
                        {{ \App\Support\Money::format($order->shipping_amount, $order->currency) }}

                        Tax
                        {{ \App\Support\Money::format($order->tax_amount, $order->currency) }}

                        Total
                        {{ \App\Support\Money::format($order->total_amount, $order->currency) }}

                <flux:heading size="lg">Refunds</flux:heading>

                    @forelse ($order->refunds as $refund)

getKey() }}">

{{ \App\Support\Money::format($refund->amount, $order->currency) }}

{{ $refund->reason ?: 'No reason' }}

                            <flux:badge>{{ Str::headline($refund->status->value) }}</flux:badge>

                    @empty

No refunds processed.

                    @endforelse

    <flux:modal name="refund-order" class="md:w-[32rem]">
        <form wire:submit="processRefund" class="space-y-6">

                <flux:heading size="lg">Process refund</flux:heading>
                <flux:text class="mt-2">Refundable amount: {{ \App\Support\Money::format($refundableAmount, $order->currency) }}</flux:text>


command: sed -n '1,220p' resources/views/livewire/storefront/account/orders/show.blade.php

aggregated_output:
<x-storefront.account-shell :customer="$customer">
    <x-storefront.breadcrumbs :items="[
        ['label' => 'Account', 'url' => route('account.dashboard')],
        ['label' => 'Orders', 'url' => route('account.orders.index')],
        ['label' => $order->order_number],
    ]" />

Order {{ $order->order_number }}

Placed on {{ $order->placed_at?->format('F j, Y') }}

                <flux:heading size="lg">Items</flux:heading>

                    @foreach ($order->lines as $line)

getKey() }}">

{{ $line->title_snapshot }}

Qty {{ $line->quantity }}

                            <x-storefront.price :amount="$line->total_amount" :currency="$order->currency" />

                    @endforeach

                    <flux:heading size="lg">Shipping Address</flux:heading>
                    @php($shippingAddress = $order->shipping_address_json ?? [])

{{ trim(data_get($shippingAddress, 'first_name').' '.data_get($shippingAddress, 'last_name')) }}

{{ data_get($shippingAddress, 'address1') }}

                        @if (data_get($shippingAddress, 'address2'))

{{ data_get($shippingAddress, 'address2') }}

                        @endif

{{ trim(data_get($shippingAddress, 'postal_code').' '.data_get($shippingAddress, 'city')) }}

{{ data_get($shippingAddress, 'country') }}

                    <flux:heading size="lg">Payment</flux:heading>

{{ Str::headline($order->payment_method->value) }}

                            <flux:badge>{{ Str::headline($order->financial_status->value) }}</flux:badge>
                            <flux:badge>{{ Str::headline($order->fulfillment_status->value) }}</flux:badge>

            @if ($order->fulfillments->isNotEmpty())

                    <flux:heading size="lg">Fulfillment</flux:heading>

                        @foreach ($order->fulfillments as $fulfillment)

getKey() }}">

                                    {{ Str::headline($fulfillment->status->value) }}
                                    @if ($fulfillment->tracking_number)
                                        {{ $fulfillment->tracking_number }}
                                    @endif

                        @endforeach

            @endif

Summary

                <flux:badge>{{ Str::headline($order->financial_status->value) }}</flux:badge>
                <flux:badge>{{ Str::headline($order->fulfillment_status->value) }}</flux:badge>

                    Subtotal
                    <x-storefront.price :amount="$order->subtotal_amount" :currency="$order->currency" />

                    Discount
                    -{{ \App\Support\Money::format($order->discount_amount, $order->currency) }}

                    Shipping
                    <x-storefront.price :amount="$order->shipping_amount" :currency="$order->currency" />

                    Tax
                    <x-storefront.price :amount="$order->tax_amount" :currency="$order->currency" />

                    Total
                    <x-storefront.price :amount="$order->total_amount" :currency="$order->currency" />

</x-storefront.account-shell>


command: rg -n "title_snapshot|sku_snapshot|discount_allocations_json|tax_lines_json" resources/views/livewire/admin/orders resources/views/livewire/storefront/account/orders resources/views/livewire/storefront/checkout -S

cmd: rg -n 'title_snapshot|sku_snapshot|discount_allocations_json|tax_lines_json' resources/views/livewire/admin/orders resources/views/livewire/storefront/account/orders resources/views/livewire/storefront/checkout -S

query: title_snapshot|sku_snapshot|discount_allocations_json|tax_lines_json

path: orders

aggregated_output:
resources/views/livewire/storefront/checkout/confirmation.blade.php:62:
{{ $line->title_snapshot }}

resources/views/livewire/admin/orders/show.blade.php:102:
{{ $line->title_snapshot }}

resources/views/livewire/admin/orders/show.blade.php:103:
{{ $line->sku_snapshot ?: 'No SKU' }}

resources/views/livewire/admin/orders/show.blade.php:205:                                        {{ $line->orderLine?->title_snapshot }} · Qty {{ $line->quantity }}
resources/views/livewire/admin/orders/show.blade.php:311:                        label="{{ $line->title_snapshot }} ({{ $remaining }} remaining)"
resources/views/livewire/storefront/account/orders/show.blade.php:21:
{{ $line->title_snapshot }}


output:
Chunk ID: e02d1a
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 258
Output:
resources/views/livewire/storefront/checkout/confirmation.blade.php:62:
{{ $line->title_snapshot }}

resources/views/livewire/admin/orders/show.blade.php:102:
{{ $line->title_snapshot }}

resources/views/livewire/admin/orders/show.blade.php:103:
{{ $line->sku_snapshot ?: 'No SKU' }}

resources/views/livewire/admin/orders/show.blade.php:205:                                        {{ $line->orderLine?->title_snapshot }} · Qty {{ $line->quantity }}
resources/views/livewire/admin/orders/show.blade.php:311:                        label="{{ $line->title_snapshot }} ({{ $remaining }} remaining)"
resources/views/livewire/storefront/account/orders/show.blade.php:21:
{{ $line->title_snapshot }}


output:
Chunk ID: 4c29a7
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 4394
Output:

            <flux:button :href="route('admin.orders.index')" wire:navigate variant="ghost" icon="arrow-left">
                Orders
            </flux:button>

                <flux:heading size="xl">{{ $order->order_number }}</flux:heading>
                <flux:text class="mt-1">{{ $order->email }} · {{ $order->placed_at?->format('M j, Y H:i') }}</flux:text>

            @if ($order->payment_method === \App\Enums\PaymentMethod::BankTransfer && $order->financial_status === \App\Enums\FinancialStatus::Pending)
                <flux:button wire:click="confirmBankTransferPayment" variant="primary" icon="banknotes" data-test="confirm-payment-button">
                    Confirm payment
                </flux:button>
            @endif

            @if (in_array($order->financial_status, [\App\Enums\FinancialStatus::Paid, \App\Enums\FinancialStatus::PartiallyRefunded], true) && $refundableAmount > 0)
                <flux:modal.trigger name="refund-order">
                    <flux:button variant="danger" icon="receipt-refund" data-test="refund-modal-button">
                        Refund
                    </flux:button>
                </flux:modal.trigger>
            @endif

            @if (in_array($order->financial_status, [\App\Enums\FinancialStatus::Paid, \App\Enums\FinancialStatus::PartiallyRefunded], true) && collect($remainingFulfillmentQuantities)->sum() > 0)
                <flux:modal.trigger name="fulfillment-order">
                    <flux:button variant="filled" icon="truck" data-test="fulfillment-modal-button">
                        Create fulfillment
                    </flux:button>
                </flux:modal.trigger>
            @endif

    @if ($actionMessage !== '')
        <flux:callout color="green" icon="check-circle" data-test="order-action-message">{{ $actionMessage }}</flux:callout>
    @endif

    @error('orderAction')

            {{ $message }}

    @enderror

    @error('fulfillment')

            {{ $message }}

    @enderror

    @if (! in_array($order->financial_status, [\App\Enums\FinancialStatus::Paid, \App\Enums\FinancialStatus::PartiallyRefunded], true) && collect($remainingFulfillmentQuantities)->sum() > 0)
        <flux:callout color="amber" icon="exclamation-triangle" data-test="fulfillment-guard-message">
            Cannot create fulfillment. Payment must be confirmed before items can be fulfilled. Current financial status: {{ Str::headline($order->financial_status->value) }}.
        </flux:callout>
    @endif

Order

                <flux:badge>{{ Str::headline($order->status->value) }}</flux:badge>

Payment

                <flux:badge :color="$order->financial_status->value === 'paid' ? 'green' : ($order->financial_status->value === 'pending' ? 'amber' : 'zinc')">
                    {{ Str::headline($order->financial_status->value) }}
                </flux:badge>

Fulfillment

                <flux:badge :color="$order->fulfillment_status->value === 'fulfilled' ? 'green' : ($order->fulfillment_status->value === 'partial' ? 'amber' : 'zinc')">
                    {{ Str::headline($order->fulfillment_status->value) }}
                </flux:badge>

Total

                {{ \App\Support\Money::format($order->total_amount, $order->currency) }}

                    <flux:heading size="lg">Line items</flux:heading>

                    @foreach ($order->lines as $line)

getKey() }}">

{{ $line->title_snapshot }}

{{ $line->sku_snapshot ?: 'No SKU' }}

Qty {{ $line->quantity }}

{{ \App\Support\Money::format($line->total_amount, $order->currency) }}

                    @endforeach

                    <flux:heading size="lg">Payments</flux:heading>

                    @foreach ($order->payments as $payment)

getKey() }}">

{{ Str::headline($payment->method->value) }}

{{ $payment->provider_payment_id }}

                                <flux:badge>{{ Str::headline($payment->status->value) }}</flux:badge>
                                {{ \App\Support\Money::format($payment->amount, $payment->currency) }}

                    @endforeach

                    <flux:heading size="lg">Timeline</flux:heading>

Order placed

{{ $order->placed_at?->format('M j, Y H:i') }}

                    @foreach ($order->payments as $payment)

getKey() }}">

                                    {{ $payment->status === \App\Enums\PaymentStatus::Captured ? 'Payment received' : Str::headline($payment->status->value) }}

{{ Str::headline($payment->method->value) }} · {{ \App\Support\Money::format($payment->amount, $payment->currency) }}

                    @endforeach

                    @foreach ($order->fulfillments as $fulfillment)

getKey() }}">

Fulfillment created

{{ Str::headline($fulfillment->status->value) }}

                    @endforeach

                    @foreach ($order->refunds as $refund)

getKey() }}">

Refunded

{{ \App\Support\Money::format($refund->amount, $order->currency) }} · {{ Str::headline($refund->status->value) }}

                    @endforeach

                    <flux:heading size="lg">Fulfillments</flux:heading>

                    @forelse ($order->fulfillments as $fulfillment)

getKey() }}">

                                    <flux:badge>{{ Str::headline($fulfillment->status->value) }}</flux:badge>
                                    @if ($fulfillment->tracking_number)

{{ $fulfillment->tracking_company }} {{ $fulfillment->tracking_number }}

                                    @endif

                                    @if ($fulfillment->status === \App\Enums\FulfillmentShipmentStatus::Pending)
                                        <flux:button wire:click="markFulfillmentShipped({{ $fulfillment->getKey() }})" size="sm" variant="filled" data-test="mark-fulfillment-shipped-button">Mark as shipped</flux:button>
                                    @endif
                                    @if ($fulfillment->status === \App\Enums\FulfillmentShipmentStatus::Shipped)
                                        <flux:button wire:click="markFulfillmentDelivered({{ $fulfillment->getKey() }})" size="sm" variant="filled" data-test="mark-fulfillment-delivered-button">Mark as delivered</flux:button>
                                    @endif

                                @foreach ($fulfillment->lines as $line)

getKey() }}">
                                        {{ $line->orderLine?->title_snapshot }} · Qty {{ $line->quantity }}

                                @endforeach

                    @empty

No fulfillments yet.

                    @endforelse

                <flux:heading size="lg">Customer</flux:heading>

{{ $order->customer?->name ?: 'Guest checkout' }}

{{ $order->email }}

                @if ($order->customer)
                    <flux:button :href="route('admin.customers.show', $order->customer)" wire:navigate variant="filled" size="sm" class="mt-4">
                        View customer
                    </flux:button>
                @endif

                <flux:heading size="lg">Summary</flux:heading>

                        Subtotal
                        {{ \App\Support\Money::format($order->subtotal_amount, $order->currency) }}

                        Discount
                        -{{ \App\Support\Money::format($order->discount_amount, $order->currency) }}

                        Shipping
                        {{ \App\Support\Money::format($order->shipping_amount, $order->currency) }}

                        Tax
                        {{ \App\Support\Money::format($order->tax_amount, $order->currency) }}

                        Total
                        {{ \App\Support\Money::format($order->total_amount, $order->currency) }}

                <flux:heading size="lg">Refunds</flux:heading>

                    @forelse ($order->refunds as $refund)

getKey() }}">

{{ \App\Support\Money::format($refund->amount, $order->currency) }}

{{ $refund->reason ?: 'No reason' }}

                            <flux:badge>{{ Str::headline($refund->status->value) }}</flux:badge>

                    @empty

No refunds processed.

                    @endforelse

    <flux:modal name="refund-order" class="md:w-[32rem]">
        <form wire:submit="processRefund" class="space-y-6">

                <flux:heading size="lg">Process refund</flux:heading>
                <flux:text class="mt-2">Refundable amount: {{ \App\Support\Money::format($refundableAmount, $order->currency) }}</flux:text>