output:
Chunk ID: 2bcccb
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 286
Output:
CartStatus.php
CheckoutStatus.php
CollectionStatus.php
CollectionType.php
DiscountStatus.php
DiscountType.php
DiscountValueType.php
FinancialStatus.php
FulfillmentShipmentStatus.php
FulfillmentStatus.php
InventoryPolicy.php
MediaStatus.php
MediaType.php
NavigationItemType.php
OrderStatus.php
PageStatus.php
PaymentMethod.php
PaymentStatus.php
ProductStatus.php
RefundStatus.php
ShippingRateType.php
StoreDomainType.php
StoreStatus.php
StoreUserRole.php
TaxMode.php
ThemeStatus.php
VariantStatus.php
<?php

namespace App\Enums;

enum FinancialStatus: string
{
    case Pending = 'pending';
    case Authorized = 'authorized';
    case Paid = 'paid';
    case PartiallyRefunded = 'partially_refunded';
    case Refunded = 'refunded';
    case Voided = 'voided';
}
<?php

namespace App\Enums;

enum FulfillmentStatus: string
{
    case Unfulfilled = 'unfulfilled';
    case Partial = 'partial';
    case Fulfilled = 'fulfilled';
}
<?php

namespace App\Enums;

enum OrderStatus: string
{
    case Pending = 'pending';
    case Paid = 'paid';
    case Fulfilled = 'fulfilled';
    case Cancelled = 'cancelled';
    case Refunded = 'refunded';
}


cmd: sed -n '1,260p' tests/Feature/Catalog/CatalogUiTest.php


cmd: sed -n '1,240p' tests/Feature/Orders/BankTransferOrderTest.php


cmd: sed -n '1,260p' tests/Feature/Orders/FulfillmentServiceTest.php


cmd: sed -n '1,260p' tests/Feature/Orders/RefundServiceTest.php


command: sed -n '1,260p' tests/Feature/Catalog/CatalogUiTest.php

CatalogUiTest.php

type: read

aggregated_output:
<?php

use App\Livewire\Admin\Collections\Form as CollectionForm;
use App\Livewire\Admin\Products\Form as ProductForm;
use App\Livewire\Admin\Products\Index as ProductIndex;
use App\Models\Collection;
use App\Models\Product;
use App\Models\Store;
use App\Models\User;
use App\Services\ProductService;
use Database\Seeders\DatabaseSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;

uses(RefreshDatabase::class);

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

test('storefront catalog browsing routes render seeded products', function () {
    $this->withHeader('Host', 'shop.test')
        ->get('/')
        ->assertSuccessful()
        ->assertSee('Acme Fashion')
        ->assertSee('Classic Cotton T-Shirt')
        ->assertSee('24.99 EUR');

    $this->withHeader('Host', 'shop.test')
        ->get('/collections/t-shirts')
        ->assertSuccessful()
        ->assertSee('T-Shirts')
        ->assertSee('Classic Cotton T-Shirt')
        ->assertDontSee('Unreleased Winter Jacket');

    $this->withHeader('Host', 'shop.test')
        ->get('/products/classic-cotton-t-shirt')
        ->assertSuccessful()
        ->assertSee('Classic Cotton T-Shirt')
        ->assertSee('Size')
        ->assertSee('Color')
        ->assertSee('Add to cart');

    $this->withHeader('Host', 'shop.test')
        ->get('/search?q=draft')
        ->assertSuccessful()
        ->assertDontSee('Unreleased Winter Jacket');
});

test('admin catalog routes require authentication and render for store admins', function () {
    $this->get('/admin/products')->assertRedirect('/admin/login');

    $user = User::query()->where('email', 'admin@acme.test')->firstOrFail();

    $this->actingAs($user)
        ->get('/admin/products')
        ->assertSuccessful()
        ->assertSee('Classic Cotton T-Shirt')
        ->assertSee('Premium Slim Fit Jeans');

    $this->actingAs($user)
        ->get('/admin/collections')
        ->assertSuccessful()
        ->assertSee('Collections')
        ->assertSee('T-Shirts');

    $this->actingAs($user)
        ->get('/admin/inventory')
        ->assertSuccessful()
        ->assertSee('Inventory')
        ->assertSee('Limited Edition Sneakers');
});

test('admin product form creates edits archives and index filters products', function () {
    $store = Store::query()->where('handle', 'acme-fashion')->firstOrFail();
    $user = User::query()->where('email', 'admin@acme.test')->firstOrFail();
    app()->instance('current_store', $store);

    Livewire::actingAs($user)
        ->test(ProductForm::class)
        ->set('title', 'Test Product Created by E2E')
        ->set('handle', 'test-product-created-by-e2e')
        ->set('descriptionHtml', 'This product was created by the E2E test suite.')
        ->set('vendor', 'Test Vendor')
        ->set('productType', 'T-Shirts')
        ->set('variants.0.price', '29.99')
        ->set('variants.0.sku', 'E2E-TEST-001')
        ->set('variants.0.quantity', 50)
        ->call('save')
        ->assertSee('Product saved');

    $product = Product::query()->where('handle', 'test-product-created-by-e2e')->firstOrFail();

    expect($product->variants()->first()?->price_amount)->toBe(2999)
        ->and($product->variants()->first()?->inventoryItem?->quantity_on_hand)->toBe(50);

    Livewire::actingAs($user)
        ->test(ProductForm::class, ['product' => $product])
        ->set('title', 'Test Product Updated')
        ->call('save')
        ->assertSee('Product saved');

    Livewire::actingAs($user)
        ->test(ProductForm::class, ['product' => $product->refresh()])
        ->set('variants.0.sku', 'ACME-CTSH-S-WHT')
        ->call('save')
        ->assertHasErrors(['variants.0.sku']);

    expect($product->refresh()->variants()->first()?->sku)->toBe('E2E-TEST-001');

    $draftProduct = app(ProductService::class)->create($store, [
        'title' => 'Draft Product With Price Later',
        'handle' => 'draft-product-with-price-later',
        'status' => 'draft',
        'variants' => [[
            'sku' => 'DRAFT-PRICE-LATER-001',
            'price_amount' => 0,
            'currency' => $store->default_currency,
            'quantity_on_hand' => 4,
            'is_default' => true,
            'position' => 0,
        ]],
    ]);

    Livewire::actingAs($user)
        ->test(ProductForm::class, ['product' => $draftProduct])
        ->set('variants.0.price', '17.50')
        ->set('status', 'active')
        ->call('save')
        ->assertSee('Product saved');

    expect($draftProduct->refresh()->status->value)->toBe('active')
        ->and($draftProduct->variants()->first()?->price_amount)->toBe(1750);

    Livewire::actingAs($user)
        ->test(ProductForm::class, ['product' => $product->refresh()])
        ->set('status', 'archived')
        ->call('save')
        ->assertSee('Product saved');

    expect($product->refresh()->status->value)->toBe('archived');

    Livewire::actingAs($user)
        ->test(ProductIndex::class)
        ->set('statusFilter', 'draft')
        ->assertSee('Unreleased Winter Jacket')
        ->assertDontSee('Classic Cotton T-Shirt')
        ->set('statusFilter', 'active')
        ->set('search', 'Cotton')
        ->assertSee('Classic Cotton T-Shirt');
});

test('admin collection form creates and assigns products', function () {
    $store = Store::query()->where('handle', 'acme-fashion')->firstOrFail();
    $user = User::query()->where('email', 'admin@acme.test')->firstOrFail();
    $product = Product::query()->where('handle', 'classic-cotton-t-shirt')->firstOrFail();
    app()->instance('current_store', $store);

    Livewire::actingAs($user)
        ->test(CollectionForm::class)
        ->set('title', 'E2E Test Collection')
        ->set('handle', 'e2e-test-collection')
        ->set('descriptionHtml', '
Created from tests.
')
        ->call('addProduct', $product->getKey())
        ->call('save')
        ->assertSee('Collection saved');

    $collection = Collection::query()->where('handle', 'e2e-test-collection')->firstOrFail();

    expect($collection->products()->pluck('products.id')->all())->toBe([$product->getKey()]);
});

status: completed


command: sed -n '1,240p' tests/Feature/Orders/BankTransferOrderTest.php

aggregated_output:
<?php

use App\Enums\FinancialStatus;
use App\Enums\FulfillmentShipmentStatus;
use App\Enums\FulfillmentStatus;
use App\Enums\OrderStatus;
use App\Enums\PaymentMethod;
use App\Enums\PaymentStatus;
use App\Events\OrderCancelled;
use App\Events\OrderPaid;
use App\Jobs\CancelUnpaidBankTransferOrders;
use App\Models\InventoryItem;
use App\Models\Order;
use App\Models\OrderLine;
use App\Models\Payment;
use App\Models\Product;
use App\Models\ProductVariant;
use App\Models\Store;
use App\Models\StoreSettings;
use App\Services\OrderService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Event;

uses(RefreshDatabase::class);

/**
 * @return array{0: Order, 1: ProductVariant}
 */
function bankTransferOrder(bool $digital = false, int $ageDays = 1): array
{
    $store = Store::factory()->create();
    app()->instance('current_store', $store);

    StoreSettings::query()->create([
        'store_id' => $store->getKey(),
        'settings_json' => ['bank_transfer_cancel_days' => 7],
    ]);

    $product = Product::factory()->withDefaultVariant(2500)->create(['store_id' => $store->getKey()]);
    $variant = ProductVariant::withoutGlobalScopes()->where('product_id', $product->getKey())->firstOrFail();
    $variant->forceFill([
        'requires_shipping' => ! $digital,
        'weight_g' => $digital ? 0 : $variant->weight_g,
    ])->save();

    InventoryItem::withoutGlobalScopes()
        ->where('variant_id', $variant->getKey())
        ->update([
            'quantity_on_hand' => 10,
            'quantity_reserved' => 2,
        ]);

    $order = Order::factory()->bankTransfer()->create([
        'store_id' => $store->getKey(),
        'payment_method' => PaymentMethod::BankTransfer,
        'status' => OrderStatus::Pending,
        'financial_status' => FinancialStatus::Pending,
        'placed_at' => now()->subDays($ageDays),
        'subtotal_amount' => 5000,
        'shipping_amount' => 0,
        'tax_amount' => 0,
        'total_amount' => 5000,
    ]);
    OrderLine::factory()->create([
        'order_id' => $order->getKey(),
        'product_id' => $product->getKey(),
        'variant_id' => $variant->getKey(),
        'quantity' => 2,
        'unit_price_amount' => 2500,
        'total_amount' => 5000,
    ]);
    Payment::factory()->bankTransfer()->create([
        'order_id' => $order->getKey(),
        'amount' => 5000,
    ]);

    return [$order, $variant];
}

test('confirming bank transfer payment captures payment and commits reserved inventory', function () {
    [$order, $variant] = bankTransferOrder();

    Event::fake();

    $paidOrder = app(OrderService::class)->confirmBankTransferPayment($order);
    $inventory = InventoryItem::withoutGlobalScopes()->where('variant_id', $variant->getKey())->firstOrFail();

    expect($paidOrder->status)->toBe(OrderStatus::Paid)
        ->and($paidOrder->financial_status)->toBe(FinancialStatus::Paid)
        ->and($paidOrder->payments->first()->status)->toBe(PaymentStatus::Captured)
        ->and($inventory->quantity_on_hand)->toBe(8)
        ->and($inventory->quantity_reserved)->toBe(0);

    Event::assertDispatched(OrderPaid::class);
});

test('confirming digital bank transfer payment auto-fulfills the order', function () {
    [$order] = bankTransferOrder(digital: true);

    $paidOrder = app(OrderService::class)->confirmBankTransferPayment($order);

    expect($paidOrder->status)->toBe(OrderStatus::Fulfilled)
        ->and($paidOrder->fulfillment_status)->toBe(FulfillmentStatus::Fulfilled)
        ->and($paidOrder->fulfillments)->toHaveCount(1)
        ->and($paidOrder->fulfillments->first()->status)->toBe(FulfillmentShipmentStatus::Delivered);
});

test('cancel job voids stale bank transfer orders and releases reservations', function () {
    [$oldOrder, $oldVariant] = bankTransferOrder(ageDays: 8);
    [$newOrder, $newVariant] = bankTransferOrder(ageDays: 2);

    Event::fake();

    (new CancelUnpaidBankTransferOrders)->handle(app(OrderService::class));

    $oldInventory = InventoryItem::withoutGlobalScopes()->where('variant_id', $oldVariant->getKey())->firstOrFail();
    $newInventory = InventoryItem::withoutGlobalScopes()->where('variant_id', $newVariant->getKey())->firstOrFail();

    expect($oldOrder->refresh()->status)->toBe(OrderStatus::Cancelled)
        ->and($oldOrder->financial_status)->toBe(FinancialStatus::Voided)
        ->and($oldOrder->payments()->first()?->status)->toBe(PaymentStatus::Failed)
        ->and($oldInventory->quantity_on_hand)->toBe(10)
        ->and($oldInventory->quantity_reserved)->toBe(0)
        ->and($newOrder->refresh()->status)->toBe(OrderStatus::Pending)
        ->and($newInventory->quantity_reserved)->toBe(2);

    Event::assertDispatched(OrderCancelled::class);
});


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

use App\Livewire\Admin\Collections\Form as CollectionForm;
use App\Livewire\Admin\Products\Form as ProductForm;
use App\Livewire\Admin\Products\Index as ProductIndex;
use App\Models\Collection;
use App\Models\Product;
use App\Models\Store;
use App\Models\User;
use App\Services\ProductService;
use Database\Seeders\DatabaseSeeder;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;

uses(RefreshDatabase::class);

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

test('storefront catalog browsing routes render seeded products', function () {
    $this->withHeader('Host', 'shop.test')
        ->get('/')
        ->assertSuccessful()
        ->assertSee('Acme Fashion')
        ->assertSee('Classic Cotton T-Shirt')
        ->assertSee('24.99 EUR');

    $this->withHeader('Host', 'shop.test')
        ->get('/collections/t-shirts')
        ->assertSuccessful()
        ->assertSee('T-Shirts')
        ->assertSee('Classic Cotton T-Shirt')
        ->assertDontSee('Unreleased Winter Jacket');

    $this->withHeader('Host', 'shop.test')
        ->get('/products/classic-cotton-t-shirt')
        ->assertSuccessful()
        ->assertSee('Classic Cotton T-Shirt')
        ->assertSee('Size')
        ->assertSee('Color')
        ->assertSee('Add to cart');

    $this->withHeader('Host', 'shop.test')
        ->get('/search?q=draft')
        ->assertSuccessful()
        ->assertDontSee('Unreleased Winter Jacket');
});

test('admin catalog routes require authentication and render for store admins', function () {
    $this->get('/admin/products')->assertRedirect('/admin/login');

    $user = User::query()->where('email', 'admin@acme.test')->firstOrFail();

    $this->actingAs($user)
        ->get('/admin/products')
        ->assertSuccessful()
        ->assertSee('Classic Cotton T-Shirt')
        ->assertSee('Premium Slim Fit Jeans');

    $this->actingAs($user)
        ->get('/admin/collections')
        ->assertSuccessful()
        ->assertSee('Collections')
        ->assertSee('T-Shirts');

    $this->actingAs($user)
        ->get('/admin/inventory')
        ->assertSuccessful()
        ->assertSee('Inventory')
        ->assertSee('Limited Edition Sneakers');
});

test('admin product form creates edits archives and index filters products', function () {
    $store = Store::query()->where('handle', 'acme-fashion')->firstOrFail();
    $user = User::query()->where('email', 'admin@acme.test')->firstOrFail();
    app()->instance('current_store', $store);

    Livewire::actingAs($user)
        ->test(ProductForm::class)
        ->set('title', 'Test Product Created by E2E')
        ->set('handle', 'test-product-created-by-e2e')
        ->set('descriptionHtml', 'This product was created by the E2E test suite.')
        ->set('vendor', 'Test Vendor')
        ->set('productType', 'T-Shirts')
        ->set('variants.0.price', '29.99')
        ->set('variants.0.sku', 'E2E-TEST-001')
        ->set('variants.0.quantity', 50)
        ->call('save')
        ->assertSee('Product saved');

    $product = Product::query()->where('handle', 'test-product-created-by-e2e')->firstOrFail();

    expect($product->variants()->first()?->price_amount)->toBe(2999)
        ->and($product->variants()->first()?->inventoryItem?->quantity_on_hand)->toBe(50);

    Livewire::actingAs($user)
        ->test(ProductForm::class, ['product' => $product])
        ->set('title', 'Test Product Updated')
        ->call('save')
        ->assertSee('Product saved');

    Livewire::actingAs($user)
        ->test(ProductForm::class, ['product' => $product->refresh()])
        ->set('variants.0.sku', 'ACME-CTSH-S-WHT')
        ->call('save')
        ->assertHasErrors(['variants.0.sku']);

    expect($product->refresh()->variants()->first()?->sku)->toBe('E2E-TEST-001');

    $draftProduct = app(ProductService::class)->create($store, [
        'title' => 'Draft Product With Price Later',
        'handle' => 'draft-product-with-price-later',
        'status' => 'draft',
        'variants' => [[
            'sku' => 'DRAFT-PRICE-LATER-001',
            'price_amount' => 0,
            'currency' => $store->default_currency,
            'quantity_on_hand' => 4,
            'is_default' => true,
            'position' => 0,
        ]],
    ]);

    Livewire::actingAs($user)
        ->test(ProductForm::class, ['product' => $draftProduct])
        ->set('variants.0.price', '17.50')
        ->set('status', 'active')
        ->call('save')
        ->assertSee('Product saved');

    expect($draftProduct->refresh()->status->value)->toBe('active')
        ->and($draftProduct->variants()->first()?->price_amount)->toBe(1750);

    Livewire::actingAs($user)
        ->test(ProductForm::class, ['product' => $product->refresh()])
        ->set('status', 'archived')
        ->call('save')
        ->assertSee('Product saved');

    expect($product->refresh()->status->value)->toBe('archived');

    Livewire::actingAs($user)
        ->test(ProductIndex::class)
        ->set('statusFilter', 'draft')
        ->assertSee('Unreleased Winter Jacket')
        ->assertDontSee('Classic Cotton T-Shirt')
        ->set('statusFilter', 'active')
        ->set('search', 'Cotton')
        ->assertSee('Classic Cotton T-Shirt');
});

test('admin collection form creates and assigns products', function () {
    $store = Store::query()->where('handle', 'acme-fashion')->firstOrFail();
    $user = User::query()->where('email', 'admin@acme.test')->firstOrFail();
    $product = Product::query()->where('handle', 'classic-cotton-t-shirt')->firstOrFail();
    app()->instance('current_store', $store);

    Livewire::actingAs($user)
        ->test(CollectionForm::class)
        ->set('title', 'E2E Test Collection')
        ->set('handle', 'e2e-test-collection')
        ->set('descriptionHtml', '
Created from tests.
')
        ->call('addProduct', $product->getKey())
        ->call('save')
        ->assertSee('Collection saved');

    $collection = Collection::query()->where('handle', 'e2e-test-collection')->firstOrFail();

    expect($collection->products()->pluck('products.id')->all())->toBe([$product->getKey()]);
});


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

use App\Enums\FinancialStatus;
use App\Enums\FulfillmentShipmentStatus;
use App\Enums\FulfillmentStatus;
use App\Enums\OrderStatus;
use App\Enums\PaymentMethod;
use App\Enums\PaymentStatus;
use App\Events\OrderCancelled;
use App\Events\OrderPaid;
use App\Jobs\CancelUnpaidBankTransferOrders;
use App\Models\InventoryItem;
use App\Models\Order;
use App\Models\OrderLine;
use App\Models\Payment;
use App\Models\Product;
use App\Models\ProductVariant;
use App\Models\Store;
use App\Models\StoreSettings;
use App\Services\OrderService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Event;

uses(RefreshDatabase::class);

/**
 * @return array{0: Order, 1: ProductVariant}
 */
function bankTransferOrder(bool $digital = false, int $ageDays = 1): array
{
    $store = Store::factory()->create();
    app()->instance('current_store', $store);

    StoreSettings::query()->create([
        'store_id' => $store->getKey(),
        'settings_json' => ['bank_transfer_cancel_days' => 7],
    ]);

    $product = Product::factory()->withDefaultVariant(2500)->create(['store_id' => $store->getKey()]);
    $variant = ProductVariant::withoutGlobalScopes()->where('product_id', $product->getKey())->firstOrFail();
    $variant->forceFill([
        'requires_shipping' => ! $digital,
        'weight_g' => $digital ? 0 : $variant->weight_g,
    ])->save();

    InventoryItem::withoutGlobalScopes()
        ->where('variant_id', $variant->getKey())
        ->update([
            'quantity_on_hand' => 10,
            'quantity_reserved' => 2,
        ]);

    $order = Order::factory()->bankTransfer()->create([
        'store_id' => $store->getKey(),
        'payment_method' => PaymentMethod::BankTransfer,
        'status' => OrderStatus::Pending,
        'financial_status' => FinancialStatus::Pending,
        'placed_at' => now()->subDays($ageDays),
        'subtotal_amount' => 5000,
        'shipping_amount' => 0,
        'tax_amount' => 0,
        'total_amount' => 5000,
    ]);
    OrderLine::factory()->create([
        'order_id' => $order->getKey(),
        'product_id' => $product->getKey(),
        'variant_id' => $variant->getKey(),
        'quantity' => 2,
        'unit_price_amount' => 2500,
        'total_amount' => 5000,
    ]);
    Payment::factory()->bankTransfer()->create([
        'order_id' => $order->getKey(),
        'amount' => 5000,
    ]);

    return [$order, $variant];
}

test('confirming bank transfer payment captures payment and commits reserved inventory', function () {
    [$order, $variant] = bankTransferOrder();

    Event::fake();

    $paidOrder = app(OrderService::class)->confirmBankTransferPayment($order);
    $inventory = InventoryItem::withoutGlobalScopes()->where('variant_id', $variant->getKey())->firstOrFail();

    expect($paidOrder->status)->toBe(OrderStatus::Paid)
        ->and($paidOrder->financial_status)->toBe(FinancialStatus::Paid)
        ->and($paidOrder->payments->first()->status)->toBe(PaymentStatus::Captured)
        ->and($inventory->quantity_on_hand)->toBe(8)
        ->and($inventory->quantity_reserved)->toBe(0);

    Event::assertDispatched(OrderPaid::class);
});

test('confirming digital bank transfer payment auto-fulfills the order', function () {
    [$order] = bankTransferOrder(digital: true);

    $paidOrder = app(OrderService::class)->confirmBankTransferPayment($order);

    expect($paidOrder->status)->toBe(OrderStatus::Fulfilled)
        ->and($paidOrder->fulfillment_status)->toBe(FulfillmentStatus::Fulfilled)
        ->and($paidOrder->fulfillments)->toHaveCount(1)
        ->and($paidOrder->fulfillments->first()->status)->toBe(FulfillmentShipmentStatus::Delivered);
});

test('cancel job voids stale bank transfer orders and releases reservations', function () {
    [$oldOrder, $oldVariant] = bankTransferOrder(ageDays: 8);
    [$newOrder, $newVariant] = bankTransferOrder(ageDays: 2);

    Event::fake();

    (new CancelUnpaidBankTransferOrders)->handle(app(OrderService::class));

    $oldInventory = InventoryItem::withoutGlobalScopes()->where('variant_id', $oldVariant->getKey())->firstOrFail();
    $newInventory = InventoryItem::withoutGlobalScopes()->where('variant_id', $newVariant->getKey())->firstOrFail();

    expect($oldOrder->refresh()->status)->toBe(OrderStatus::Cancelled)
        ->and($oldOrder->financial_status)->toBe(FinancialStatus::Voided)
        ->and($oldOrder->payments()->first()?->status)->toBe(PaymentStatus::Failed)
        ->and($oldInventory->quantity_on_hand)->toBe(10)
        ->and($oldInventory->quantity_reserved)->toBe(0)
        ->and($newOrder->refresh()->status)->toBe(OrderStatus::Pending)
        ->and($newInventory->quantity_reserved)->toBe(2);

    Event::assertDispatched(OrderCancelled::class);
});


command: sed -n '1,260p' tests/Feature/Orders/RefundServiceTest.php

aggregated_output:
<?php

use App\Enums\FinancialStatus;
use App\Enums\OrderStatus;
use App\Enums\PaymentStatus;
use App\Enums\RefundStatus;
use App\Events\OrderRefunded;
use App\Exceptions\InvalidRefundOperationException;
use App\Models\InventoryItem;
use App\Models\Order;
use App\Models\OrderLine;
use App\Models\Payment;
use App\Models\Product;
use App\Models\ProductVariant;
use App\Models\Store;
use App\Services\RefundService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Event;

uses(RefreshDatabase::class);

/**
 * @return array{0: Order, 1: OrderLine, 2: ProductVariant}
 */
function refundServiceOrder(int $quantity = 2, int $unitPrice = 5000): array
{
    $store = Store::factory()->create();
    app()->instance('current_store', $store);

    $product = Product::factory()
        ->withDefaultVariant($unitPrice)
        ->create(['store_id' => $store->getKey()]);
    $variant = ProductVariant::withoutGlobalScopes()
        ->where('product_id', $product->getKey())
        ->firstOrFail();

    InventoryItem::withoutGlobalScopes()
        ->where('variant_id', $variant->getKey())
        ->update([
            'quantity_on_hand' => 8,
            'quantity_reserved' => 0,
        ]);

    $total = $quantity * $unitPrice;
    $order = Order::factory()->paid()->create([
        'store_id' => $store->getKey(),
        'subtotal_amount' => $total,
        'shipping_amount' => 0,
        'tax_amount' => 0,
        'total_amount' => $total,
    ]);
    $line = OrderLine::factory()->create([
        'order_id' => $order->getKey(),
        'product_id' => $product->getKey(),
        'variant_id' => $variant->getKey(),
        'quantity' => $quantity,
        'unit_price_amount' => $unitPrice,
        'total_amount' => $total,
    ]);

    Payment::factory()->create([
        'order_id' => $order->getKey(),
        'status' => PaymentStatus::Captured,
        'amount' => $total,
    ]);

    return [$order, $line, $variant];
}

test('refund service processes a partial line refund and restocks inventory', function () {
    [$order, $line, $variant] = refundServiceOrder();

    Event::fake();

    $refund = app(RefundService::class)->process($order, [
        'lines' => [$line->getKey() => 1],
        'reason' => 'Customer return',
        'restock' => true,
    ]);

    expect($refund->amount)->toBe(5000)
        ->and($refund->status)->toBe(RefundStatus::Processed)
        ->and($refund->provider_refund_id)->toStartWith('mock_refund_')
        ->and($order->refresh()->status)->toBe(OrderStatus::Paid)
        ->and($order->financial_status)->toBe(FinancialStatus::PartiallyRefunded)
        ->and($order->payments()->first()?->status)->toBe(PaymentStatus::Captured)
        ->and(InventoryItem::withoutGlobalScopes()->where('variant_id', $variant->getKey())->first()?->quantity_on_hand)->toBe(9);

    Event::assertDispatched(OrderRefunded::class, fn (OrderRefunded $event): bool => $event->refund->is($refund));
});

test('refund service marks order and payment refunded when the full amount is refunded', function () {
    [$order] = refundServiceOrder();

    $refund = app(RefundService::class)->process($order);

    expect($refund->amount)->toBe(10000)
        ->and($order->refresh()->status)->toBe(OrderStatus::Refunded)
        ->and($order->financial_status)->toBe(FinancialStatus::Refunded)
        ->and($order->payments()->first()?->status)->toBe(PaymentStatus::Refunded);
});

test('refund service rejects over-refunds and orders without captured payments', function () {
    [$order] = refundServiceOrder();

    expect(fn () => app(RefundService::class)->process($order, ['amount' => 10001]))
        ->toThrow(InvalidRefundOperationException::class);

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

    expect(fn () => app(RefundService::class)->process($order, ['amount' => 500]))
        ->toThrow(InvalidRefundOperationException::class);
});


command: sed -n '1,260p' tests/Feature/Orders/FulfillmentServiceTest.php

aggregated_output:
<?php

use App\Enums\FinancialStatus;
use App\Enums\FulfillmentShipmentStatus;
use App\Enums\FulfillmentStatus;
use App\Enums\OrderStatus;
use App\Events\FulfillmentCreated;
use App\Events\FulfillmentDelivered;
use App\Events\FulfillmentShipped;
use App\Exceptions\InvalidFulfillmentOperationException;
use App\Models\Order;
use App\Models\OrderLine;
use App\Models\Product;
use App\Models\ProductVariant;
use App\Models\Store;
use App\Services\FulfillmentService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Event;

uses(RefreshDatabase::class);

/**
 * @return array{0: Order, 1: OrderLine, 2: OrderLine}
 */
function fulfillmentServiceOrder(FinancialStatus $financialStatus = FinancialStatus::Paid): array
{
    $store = Store::factory()->create();
    app()->instance('current_store', $store);

    $firstProduct = Product::factory()->withDefaultVariant(2500)->create(['store_id' => $store->getKey()]);
    $secondProduct = Product::factory()->withDefaultVariant(1500)->create(['store_id' => $store->getKey()]);
    $firstVariant = ProductVariant::withoutGlobalScopes()->where('product_id', $firstProduct->getKey())->firstOrFail();
    $secondVariant = ProductVariant::withoutGlobalScopes()->where('product_id', $secondProduct->getKey())->firstOrFail();

    $order = Order::factory()->paid()->create([
        'store_id' => $store->getKey(),
        'financial_status' => $financialStatus,
        'status' => $financialStatus === FinancialStatus::Pending ? OrderStatus::Pending : OrderStatus::Paid,
    ]);
    $firstLine = OrderLine::factory()->create([
        'order_id' => $order->getKey(),
        'product_id' => $firstProduct->getKey(),
        'variant_id' => $firstVariant->getKey(),
        'quantity' => 2,
        'unit_price_amount' => 2500,
        'total_amount' => 5000,
    ]);
    $secondLine = OrderLine::factory()->create([
        'order_id' => $order->getKey(),
        'product_id' => $secondProduct->getKey(),
        'variant_id' => $secondVariant->getKey(),
        'quantity' => 1,
        'unit_price_amount' => 1500,
        'total_amount' => 1500,
    ]);

    return [$order, $firstLine, $secondLine];
}

test('fulfillment service blocks fulfillment until payment is confirmed', function () {
    [$order, $line] = fulfillmentServiceOrder(FinancialStatus::Pending);

    expect(fn () => app(FulfillmentService::class)->create($order, [$line->getKey() => 1]))
        ->toThrow(InvalidFulfillmentOperationException::class);
});

test('fulfillment service creates partial and complete fulfillments', function () {
    [$order, $firstLine, $secondLine] = fulfillmentServiceOrder();

    Event::fake();

    $firstFulfillment = app(FulfillmentService::class)->create($order, [
        $firstLine->getKey() => 2,
    ], [
        'tracking_company' => 'DHL',
        'tracking_number' => 'DHL123',
    ]);

    expect($firstFulfillment->status)->toBe(FulfillmentShipmentStatus::Pending)
        ->and($order->refresh()->fulfillment_status)->toBe(FulfillmentStatus::Partial)
        ->and($order->status)->toBe(OrderStatus::Paid);

    $secondFulfillment = app(FulfillmentService::class)->create($order, [
        $secondLine->getKey() => 1,
    ]);

    expect($secondFulfillment->lines)->toHaveCount(1)
        ->and($order->refresh()->fulfillment_status)->toBe(FulfillmentStatus::Fulfilled)
        ->and($order->status)->toBe(OrderStatus::Fulfilled);

    Event::assertDispatched(FulfillmentCreated::class, 2);
});

test('fulfillment service rejects over-fulfillment and invalid transitions', function () {
    [$order, $line] = fulfillmentServiceOrder();
    $fulfillment = app(FulfillmentService::class)->create($order, [$line->getKey() => 1]);

    expect(fn () => app(FulfillmentService::class)->create($order, [$line->getKey() => 2]))
        ->toThrow(InvalidFulfillmentOperationException::class);

    expect(fn () => app(FulfillmentService::class)->markDelivered($fulfillment))
        ->toThrow(InvalidFulfillmentOperationException::class);
});

test('fulfillment service marks shipments as shipped and delivered', function () {
    [$order, $line] = fulfillmentServiceOrder();
    $fulfillment = app(FulfillmentService::class)->create($order, [$line->getKey() => 1]);

    Event::fake();

    $shipped = app(FulfillmentService::class)->markShipped($fulfillment);
    $delivered = app(FulfillmentService::class)->markDelivered($shipped);

    expect($shipped->status)->toBe(FulfillmentShipmentStatus::Shipped)
        ->and($shipped->shipped_at)->not->toBeNull()
        ->and($delivered->status)->toBe(FulfillmentShipmentStatus::Delivered)
        ->and($delivered->delivered_at)->not->toBeNull();

    Event::assertDispatched(FulfillmentShipped::class);
    Event::assertDispatched(FulfillmentDelivered::class);
});


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

use App\Enums\FinancialStatus;
use App\Enums\FulfillmentShipmentStatus;
use App\Enums\FulfillmentStatus;
use App\Enums\OrderStatus;
use App\Events\FulfillmentCreated;
use App\Events\FulfillmentDelivered;
use App\Events\FulfillmentShipped;
use App\Exceptions\InvalidFulfillmentOperationException;
use App\Models\Order;
use App\Models\OrderLine;
use App\Models\Product;
use App\Models\ProductVariant;
use App\Models\Store;
use App\Services\FulfillmentService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Event;

uses(RefreshDatabase::class);

/**
 * @return array{0: Order, 1: OrderLine, 2: OrderLine}
 */
function fulfillmentServiceOrder(FinancialStatus $financialStatus = FinancialStatus::Paid): array
{
    $store = Store::factory()->create();
    app()->instance('current_store', $store);

    $firstProduct = Product::factory()->withDefaultVariant(2500)->create(['store_id' => $store->getKey()]);
    $secondProduct = Product::factory()->withDefaultVariant(1500)->create(['store_id' => $store->getKey()]);
    $firstVariant = ProductVariant::withoutGlobalScopes()->where('product_id', $firstProduct->getKey())->firstOrFail();
    $secondVariant = ProductVariant::withoutGlobalScopes()->where('product_id', $secondProduct->getKey())->firstOrFail();

    $order = Order::factory()->paid()->create([
        'store_id' => $store->getKey(),
        'financial_status' => $financialStatus,
        'status' => $financialStatus === FinancialStatus::Pending ? OrderStatus::Pending : OrderStatus::Paid,
    ]);
    $firstLine = OrderLine::factory()->create([
        'order_id' => $order->getKey(),
        'product_id' => $firstProduct->getKey(),
        'variant_id' => $firstVariant->getKey(),
        'quantity' => 2,
        'unit_price_amount' => 2500,
        'total_amount' => 5000,
    ]);
    $secondLine = OrderLine::factory()->create([
        'order_id' => $order->getKey(),
        'product_id' => $secondProduct->getKey(),
        'variant_id' => $secondVariant->getKey(),
        'quantity' => 1,
        'unit_price_amount' => 1500,
        'total_amount' => 1500,
    ]);

    return [$order, $firstLine, $secondLine];
}

test('fulfillment service blocks fulfillment until payment is confirmed', function () {
    [$order, $line] = fulfillmentServiceOrder(FinancialStatus::Pending);

    expect(fn () => app(FulfillmentService::class)->create($order, [$line->getKey() => 1]))
        ->toThrow(InvalidFulfillmentOperationException::class);
});

test('fulfillment service creates partial and complete fulfillments', function () {
    [$order, $firstLine, $secondLine] = fulfillmentServiceOrder();

    Event::fake();

    $firstFulfillment = app(FulfillmentService::class)->create($order, [
        $firstLine->getKey() => 2,
    ], [
        'tracking_company' => 'DHL',
        'tracking_number' => 'DHL123',
    ]);

    expect($firstFulfillment->status)->toBe(FulfillmentShipmentStatus::Pending)
        ->and($order->refresh()->fulfillment_status)->toBe(FulfillmentStatus::Partial)
        ->and($order->status)->toBe(OrderStatus::Paid);

    $secondFulfillment = app(FulfillmentService::class)->create($order, [
        $secondLine->getKey() => 1,
    ]);

    expect($secondFulfillment->lines)->toHaveCount(1)
        ->and($order->refresh()->fulfillment_status)->toBe(FulfillmentStatus::Fulfilled)
        ->and($order->status)->toBe(OrderStatus::Fulfilled);

    Event::assertDispatched(FulfillmentCreated::class, 2);
});

test('fulfillment service rejects over-fulfillment and invalid transitions', function () {
    [$order, $line] = fulfillmentServiceOrder();
    $fulfillment = app(FulfillmentService::class)->create($order, [$line->getKey() => 1]);

    expect(fn () => app(FulfillmentService::class)->create($order, [$line->getKey() => 2]))
        ->toThrow(InvalidFulfillmentOperationException::class);

    expect(fn () => app(FulfillmentService::class)->markDelivered($fulfillment))
        ->toThrow(InvalidFulfillmentOperationException::class);
});

test('fulfillment service marks shipments as shipped and delivered', function () {
    [$order, $line] = fulfillmentServiceOrder();
    $fulfillment = app(FulfillmentService::class)->create($order, [$line->getKey() => 1]);

    Event::fake();

    $shipped = app(FulfillmentService::class)->markShipped($fulfillment);
    $delivered = app(FulfillmentService::class)->markDelivered($shipped);

    expect($shipped->status)->toBe(FulfillmentShipmentStatus::Shipped)
        ->and($shipped->shipped_at)->not->toBeNull()
        ->and($delivered->status)->toBe(FulfillmentShipmentStatus::Delivered)
        ->and($delivered->delivered_at)->not->toBeNull();

    Event::assertDispatched(FulfillmentShipped::class);
    Event::assertDispatched(FulfillmentDelivered::class);
});


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

use App\Enums\FinancialStatus;
use App\Enums\OrderStatus;
use App\Enums\PaymentStatus;
use App\Enums\RefundStatus;
use App\Events\OrderRefunded;
use App\Exceptions\InvalidRefundOperationException;
use App\Models\InventoryItem;
use App\Models\Order;
use App\Models\OrderLine;
use App\Models\Payment;
use App\Models\Product;
use App\Models\ProductVariant;
use App\Models\Store;
use App\Services\RefundService;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Support\Facades\Event;

uses(RefreshDatabase::class);

/**
 * @return array{0: Order, 1: OrderLine, 2: ProductVariant}
 */
function refundServiceOrder(int $quantity = 2, int $unitPrice = 5000): array
{
    $store = Store::factory()->create();
    app()->instance('current_store', $store);

    $product = Product::factory()
        ->withDefaultVariant($unitPrice)
        ->create(['store_id' => $store->getKey()]);
    $variant = ProductVariant::withoutGlobalScopes()
        ->where('product_id', $product->getKey())
        ->firstOrFail();

    InventoryItem::withoutGlobalScopes()
        ->where('variant_id', $variant->getKey())
        ->update([
            'quantity_on_hand' => 8,
            'quantity_reserved' => 0,
        ]);

    $total = $quantity * $unitPrice;
    $order = Order::factory()->paid()->create([
        'store_id' => $store->getKey(),
        'subtotal_amount' => $total,
        'shipping_amount' => 0,
        'tax_amount' => 0,
        'total_amount' => $total,
    ]);
    $line = OrderLine::factory()->create([
        'order_id' => $order->getKey(),
        'product_id' => $product->getKey(),
        'variant_id' => $variant->getKey(),
        'quantity' => $quantity,
        'unit_price_amount' => $unitPrice,
        'total_amount' => $total,
    ]);

    Payment::factory()->create([
        'order_id' => $order->getKey(),
        'status' => PaymentStatus::Captured,
        'amount' => $total,
    ]);

    return [$order, $line, $variant];
}

test('refund service processes a partial line refund and restocks inventory', function () {
    [$order, $line, $variant] = refundServiceOrder();

    Event::fake();

    $refund = app(RefundService::class)->process($order, [
        'lines' => [$line->getKey() => 1],
        'reason' => 'Customer return',
        'restock' => true,
    ]);

    expect($refund->amount)->toBe(5000)
        ->and($refund->status)->toBe(RefundStatus::Processed)
        ->and($refund->provider_refund_id)->toStartWith('mock_refund_')
        ->and($order->refresh()->status)->toBe(OrderStatus::Paid)
        ->and($order->financial_status)->toBe(FinancialStatus::PartiallyRefunded)
        ->and($order->payments()->first()?->status)->toBe(PaymentStatus::Captured)
        ->and(InventoryItem::withoutGlobalScopes()->where('variant_id', $variant->getKey())->first()?->quantity_on_hand)->toBe(9);

    Event::assertDispatched(OrderRefunded::class, fn (OrderRefunded $event): bool => $event->refund->is($refund));
});

test('refund service marks order and payment refunded when the full amount is refunded', function () {
    [$order] = refundServiceOrder();

    $refund = app(RefundService::class)->process($order);

    expect($refund->amount)->toBe(10000)
        ->and($order->refresh()->status)->toBe(OrderStatus::Refunded)
        ->and($order->financial_status)->toBe(FinancialStatus::Refunded)
        ->and($order->payments()->first()?->status)->toBe(PaymentStatus::Refunded);
});

test('refund service rejects over-refunds and orders without captured payments', function () {
    [$order] = refundServiceOrder();

    expect(fn () => app(RefundService::class)->process($order, ['amount' => 10001]))
        ->toThrow(InvalidRefundOperationException::class);

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

    expect(fn () => app(RefundService::class)->process($order, ['amount' => 500]))
        ->toThrow(InvalidRefundOperationException::class);
});


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


cmd: sed -n '1,220p' database/factories/OrderFactory.php


cmd: sed -n '1,220p' database/factories/PaymentFactory.php && sed -n '1,180p' database/factories/FulfillmentFactory.php


command: sed -n '1,240p' app/Models/OrderLine.php

aggregated_output:
<?php

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class OrderLine extends Model
{
    /** @use HasFactory<\Database\Factories\OrderLineFactory> */
    use HasFactory;

    public $timestamps = false;

    /**
     * @var list<string>
     */
    protected $fillable = [
        'order_id',
        'product_id',
        'variant_id',
        'title_snapshot',
        'sku_snapshot',
        'quantity',
        'unit_price_amount',
        'total_amount',
        'tax_lines_json',
        'discount_allocations_json',
    ];

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

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

    /**
     * @return BelongsTo<ProductVariant, $this>
     */
    public function variant(): BelongsTo
    {
        return $this->belongsTo(ProductVariant::class, 'variant_id');
    }

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

    /**
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            'quantity' => 'integer',
            'unit_price_amount' => 'integer',
            'total_amount' => 'integer',
            'tax_lines_json' => 'array',
            'discount_allocations_json' => 'array',
        ];
    }
}


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

Order.php

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

aggregated_output:
<?php

namespace App\Models;

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

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

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

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

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

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

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

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

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

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

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

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


command: sed -n '1,220p' database/factories/OrderFactory.php

aggregated_output:
<?php

namespace Database\Factories;

use App\Enums\FinancialStatus;
use App\Enums\FulfillmentStatus;
use App\Enums\OrderStatus;
use App\Enums\PaymentMethod;
use App\Models\Checkout;
use App\Models\Customer;
use App\Models\Store;
use Illuminate\Database\Eloquent\Factories\Factory;

/**
 * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Order>
 */
class OrderFactory extends Factory
{
    /**
     * Define the model's default state.
     *
     * @return array<string, mixed>
     */
    public function definition(): array
    {
        $subtotal = fake()->numberBetween(2500, 25000);
        $shipping = fake()->randomElement([0, 499, 799]);
        $tax = 0;

        return [
            'store_id' => Store::factory(),
            'checkout_id' => null,
            'customer_id' => null,
            'order_number' => '#'.fake()->unique()->numberBetween(1001, 9999),
            'payment_method' => PaymentMethod::CreditCard,
            'status' => OrderStatus::Paid,
            'financial_status' => FinancialStatus::Paid,
            'fulfillment_status' => FulfillmentStatus::Unfulfilled,
            'currency' => 'EUR',
            'subtotal_amount' => $subtotal,
            'discount_amount' => 0,
            'shipping_amount' => $shipping,
            'tax_amount' => $tax,
            'total_amount' => $subtotal + $shipping + $tax,
            'email' => fake()->safeEmail(),
            'billing_address_json' => $this->address(),
            'shipping_address_json' => $this->address(),
            'placed_at' => now(),
        ];
    }

    public function forCheckout(?Checkout $checkout = null): static
    {
        return $this->state(fn (array $attributes): array => [
            'checkout_id' => $checkout?->getKey() ?? Checkout::factory(),
        ]);
    }

    public function forCustomer(?Customer $customer = null): static
    {
        return $this->state(fn (array $attributes): array => [
            'customer_id' => $customer?->getKey() ?? Customer::factory(),
        ]);
    }

    public function paid(): static
    {
        return $this->state(fn (array $attributes): array => [
            'status' => OrderStatus::Paid,
            'financial_status' => FinancialStatus::Paid,
        ]);
    }

    public function pending(): static
    {
        return $this->state(fn (array $attributes): array => [
            'status' => OrderStatus::Pending,
            'financial_status' => FinancialStatus::Pending,
        ]);
    }

    public function creditCard(): static
    {
        return $this->state(fn (array $attributes): array => [
            'payment_method' => PaymentMethod::CreditCard,
        ]);
    }

    public function paypal(): static
    {
        return $this->state(fn (array $attributes): array => [
            'payment_method' => PaymentMethod::Paypal,
        ]);
    }

    public function bankTransfer(): static
    {
        return $this->state(fn (array $attributes): array => [
            'payment_method' => PaymentMethod::BankTransfer,
            'status' => OrderStatus::Pending,
            'financial_status' => FinancialStatus::Pending,
        ]);
    }

    public function cancelled(): static
    {
        return $this->state(fn (array $attributes): array => [
            'status' => OrderStatus::Cancelled,
            'financial_status' => FinancialStatus::Voided,
        ]);
    }

    public function partiallyFulfilled(): static
    {
        return $this->state(fn (array $attributes): array => [
            'fulfillment_status' => FulfillmentStatus::Partial,
        ]);
    }

    public function fulfilled(): static
    {
        return $this->state(fn (array $attributes): array => [
            'status' => OrderStatus::Fulfilled,
            'financial_status' => FinancialStatus::Paid,
            'fulfillment_status' => FulfillmentStatus::Fulfilled,
        ]);
    }

    public function refunded(): static
    {
        return $this->state(fn (array $attributes): array => [
            'status' => OrderStatus::Refunded,
            'financial_status' => FinancialStatus::Refunded,
        ]);
    }

    /**
     * @return array<string, string|null>
     */
    private function address(): array
    {
        return [
            'first_name' => fake()->firstName(),
            'last_name' => fake()->lastName(),
            'address1' => fake()->streetAddress(),
            'address2' => null,
            'city' => fake()->city(),
            'province_code' => null,
            'country' => 'DE',
            'postal_code' => fake()->postcode(),
        ];
    }
}


command: sed -n '1,220p' database/factories/PaymentFactory.php && sed -n '1,180p' database/factories/FulfillmentFactory.php

FulfillmentFactory.php

aggregated_output:
<?php

namespace Database\Factories;

use App\Enums\PaymentMethod;
use App\Enums\PaymentStatus;
use App\Models\Order;
use Illuminate\Database\Eloquent\Factories\Factory;

/**
 * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Payment>
 */
class PaymentFactory extends Factory
{
    /**
     * Define the model's default state.
     *
     * @return array<string, mixed>
     */
    public function definition(): array
    {
        return [
            'order_id' => Order::factory(),
            'provider' => 'mock',
            'method' => PaymentMethod::CreditCard,
            'provider_payment_id' => 'mock_payment_'.fake()->unique()->lexify('????????????????'),
            'status' => PaymentStatus::Captured,
            'amount' => fake()->numberBetween(2500, 25000),
            'currency' => 'EUR',
            'raw_json_encrypted' => [
                'success' => true,
                'status' => PaymentStatus::Captured->value,
            ],
        ];
    }

    public function pending(): static
    {
        return $this->state(fn (array $attributes): array => [
            'status' => PaymentStatus::Pending,
        ]);
    }

    public function failed(): static
    {
        return $this->state(fn (array $attributes): array => [
            'status' => PaymentStatus::Failed,
            'raw_json_encrypted' => [
                'success' => false,
                'status' => PaymentStatus::Failed->value,
                'error_code' => 'card_declined',
            ],
        ]);
    }

    public function refunded(): static
    {
        return $this->state(fn (array $attributes): array => [
            'status' => PaymentStatus::Refunded,
        ]);
    }

    public function paypal(): static
    {
        return $this->state(fn (array $attributes): array => [
            'method' => PaymentMethod::Paypal,
        ]);
    }

    public function bankTransfer(): static
    {
        return $this->state(fn (array $attributes): array => [
            'method' => PaymentMethod::BankTransfer,
            'status' => PaymentStatus::Pending,
            'provider_payment_id' => 'mock_bank_'.fake()->unique()->lexify('????????????????'),
        ]);
    }
}
<?php

namespace Database\Factories;

use App\Enums\FulfillmentShipmentStatus;
use App\Models\Order;
use Illuminate\Database\Eloquent\Factories\Factory;

/**
 * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Fulfillment>
 */
class FulfillmentFactory extends Factory
{
    /**
     * Define the model's default state.
     *
     * @return array<string, mixed>
     */
    public function definition(): array
    {
        return [
            'order_id' => Order::factory(),
            'status' => FulfillmentShipmentStatus::Pending,
            'tracking_company' => null,
            'tracking_number' => null,
            'tracking_url' => null,
            'shipped_at' => null,
            'delivered_at' => null,
        ];
    }

    public function withTracking(): static
    {
        return $this->state(fn (array $attributes): array => [
            'tracking_company' => fake()->randomElement(['DHL', 'UPS', 'DPD']),
            'tracking_number' => fake()->bothify('??##########'),
            'tracking_url' => fake()->url(),
        ]);
    }

    public function shipped(): static
    {
        return $this->withTracking()->state(fn (array $attributes): array => [
            'status' => FulfillmentShipmentStatus::Shipped,
            'shipped_at' => now(),
        ]);
    }

    public function delivered(): static
    {
        return $this->withTracking()->state(fn (array $attributes): array => [
            'status' => FulfillmentShipmentStatus::Delivered,
            'shipped_at' => now()->subDay(),
            'delivered_at' => now(),
        ]);
    }
}


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

namespace App\Models;

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

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

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

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

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

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

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

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

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

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

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

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


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

namespace App\Models;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;

class OrderLine extends Model
{
    /** @use HasFactory<\Database\Factories\OrderLineFactory> */
    use HasFactory;

    public $timestamps = false;

    /**
     * @var list<string>
     */
    protected $fillable = [
        'order_id',
        'product_id',
        'variant_id',
        'title_snapshot',
        'sku_snapshot',
        'quantity',
        'unit_price_amount',
        'total_amount',
        'tax_lines_json',
        'discount_allocations_json',
    ];

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

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

    /**
     * @return BelongsTo<ProductVariant, $this>
     */
    public function variant(): BelongsTo
    {
        return $this->belongsTo(ProductVariant::class, 'variant_id');
    }

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

    /**
     * @return array<string, string>
     */
    protected function casts(): array
    {
        return [
            'quantity' => 'integer',
            'unit_price_amount' => 'integer',
            'total_amount' => 'integer',
            'tax_lines_json' => 'array',
            'discount_allocations_json' => 'array',
        ];
    }
}


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

namespace Database\Factories;

use App\Enums\FinancialStatus;
use App\Enums\FulfillmentStatus;
use App\Enums\OrderStatus;
use App\Enums\PaymentMethod;
use App\Models\Checkout;
use App\Models\Customer;
use App\Models\Store;
use Illuminate\Database\Eloquent\Factories\Factory;

/**
 * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Order>
 */
class OrderFactory extends Factory
{
    /**
     * Define the model's default state.
     *
     * @return array<string, mixed>
     */
    public function definition(): array
    {
        $subtotal = fake()->numberBetween(2500, 25000);
        $shipping = fake()->randomElement([0, 499, 799]);
        $tax = 0;

        return [
            'store_id' => Store::factory(),
            'checkout_id' => null,
            'customer_id' => null,
            'order_number' => '#'.fake()->unique()->numberBetween(1001, 9999),
            'payment_method' => PaymentMethod::CreditCard,
            'status' => OrderStatus::Paid,
            'financial_status' => FinancialStatus::Paid,
            'fulfillment_status' => FulfillmentStatus::Unfulfilled,
            'currency' => 'EUR',
            'subtotal_amount' => $subtotal,
            'discount_amount' => 0,
            'shipping_amount' => $shipping,
            'tax_amount' => $tax,
            'total_amount' => $subtotal + $shipping + $tax,
            'email' => fake()->safeEmail(),
            'billing_address_json' => $this->address(),
            'shipping_address_json' => $this->address(),
            'placed_at' => now(),
        ];
    }

    public function forCheckout(?Checkout $checkout = null): static
    {
        return $this->state(fn (array $attributes): array => [
            'checkout_id' => $checkout?->getKey() ?? Checkout::factory(),
        ]);
    }

    public function forCustomer(?Customer $customer = null): static
    {
        return $this->state(fn (array $attributes): array => [
            'customer_id' => $customer?->getKey() ?? Customer::factory(),
        ]);
    }

    public function paid(): static
    {
        return $this->state(fn (array $attributes): array => [
            'status' => OrderStatus::Paid,
            'financial_status' => FinancialStatus::Paid,
        ]);
    }

    public function pending(): static
    {
        return $this->state(fn (array $attributes): array => [
            'status' => OrderStatus::Pending,
            'financial_status' => FinancialStatus::Pending,
        ]);
    }

    public function creditCard(): static
    {
        return $this->state(fn (array $attributes): array => [
            'payment_method' => PaymentMethod::CreditCard,
        ]);
    }

    public function paypal(): static
    {
        return $this->state(fn (array $attributes): array => [
            'payment_method' => PaymentMethod::Paypal,
        ]);
    }

    public function bankTransfer(): static
    {
        return $this->state(fn (array $attributes): array => [
            'payment_method' => PaymentMethod::BankTransfer,
            'status' => OrderStatus::Pending,
            'financial_status' => FinancialStatus::Pending,
        ]);
    }

    public function cancelled(): static
    {
        return $this->state(fn (array $attributes): array => [
            'status' => OrderStatus::Cancelled,
            'financial_status' => FinancialStatus::Voided,
        ]);
    }

    public function partiallyFulfilled(): static
    {
        return $this->state(fn (array $attributes): array => [
            'fulfillment_status' => FulfillmentStatus::Partial,
        ]);
    }

    public function fulfilled(): static
    {
        return $this->state(fn (array $attributes): array => [
            'status' => OrderStatus::Fulfilled,
            'financial_status' => FinancialStatus::Paid,
            'fulfillment_status' => FulfillmentStatus::Fulfilled,
        ]);
    }

    public function refunded(): static
    {
        return $this->state(fn (array $attributes): array => [
            'status' => OrderStatus::Refunded,
            'financial_status' => FinancialStatus::Refunded,
        ]);
    }

    /**
     * @return array<string, string|null>
     */
    private function address(): array
    {
        return [
            'first_name' => fake()->firstName(),
            'last_name' => fake()->lastName(),
            'address1' => fake()->streetAddress(),
            'address2' => null,
            'city' => fake()->city(),
            'province_code' => null,
            'country' => 'DE',
            'postal_code' => fake()->postcode(),
        ];
    }
}


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

namespace Database\Factories;

use App\Enums\PaymentMethod;
use App\Enums\PaymentStatus;
use App\Models\Order;
use Illuminate\Database\Eloquent\Factories\Factory;

/**
 * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Payment>
 */
class PaymentFactory extends Factory
{
    /**
     * Define the model's default state.
     *
     * @return array<string, mixed>
     */
    public function definition(): array
    {
        return [
            'order_id' => Order::factory(),
            'provider' => 'mock',
            'method' => PaymentMethod::CreditCard,
            'provider_payment_id' => 'mock_payment_'.fake()->unique()->lexify('????????????????'),
            'status' => PaymentStatus::Captured,
            'amount' => fake()->numberBetween(2500, 25000),
            'currency' => 'EUR',
            'raw_json_encrypted' => [
                'success' => true,
                'status' => PaymentStatus::Captured->value,
            ],
        ];
    }

    public function pending(): static
    {
        return $this->state(fn (array $attributes): array => [
            'status' => PaymentStatus::Pending,
        ]);
    }

    public function failed(): static
    {
        return $this->state(fn (array $attributes): array => [
            'status' => PaymentStatus::Failed,
            'raw_json_encrypted' => [
                'success' => false,
                'status' => PaymentStatus::Failed->value,
                'error_code' => 'card_declined',
            ],
        ]);
    }

    public function refunded(): static
    {
        return $this->state(fn (array $attributes): array => [
            'status' => PaymentStatus::Refunded,
        ]);
    }

    public function paypal(): static
    {
        return $this->state(fn (array $attributes): array => [
            'method' => PaymentMethod::Paypal,
        ]);
    }

    public function bankTransfer(): static
    {
        return $this->state(fn (array $attributes): array => [
            'method' => PaymentMethod::BankTransfer,
            'status' => PaymentStatus::Pending,
            'provider_payment_id' => 'mock_bank_'.fake()->unique()->lexify('????????????????'),
        ]);
    }
}
<?php

namespace Database\Factories;

use App\Enums\FulfillmentShipmentStatus;
use App\Models\Order;
use Illuminate\Database\Eloquent\Factories\Factory;

/**
 * @extends \Illuminate\Database\Eloquent\Factories\Factory<\App\Models\Fulfillment>
 */
class FulfillmentFactory extends Factory
{
    /**
     * Define the model's default state.
     *
     * @return array<string, mixed>
     */
    public function definition(): array
    {
        return [
            'order_id' => Order::factory(),
            'status' => FulfillmentShipmentStatus::Pending,
            'tracking_company' => null,
            'tracking_number' => null,
            'tracking_url' => null,
            'shipped_at' => null,
            'delivered_at' => null,
        ];
    }

    public function withTracking(): static
    {
        return $this->state(fn (array $attributes): array => [
            'tracking_company' => fake()->randomElement(['DHL', 'UPS', 'DPD']),
            'tracking_number' => fake()->bothify('??##########'),
            'tracking_url' => fake()->url(),
        ]);
    }

    public function shipped(): static
    {
        return $this->withTracking()->state(fn (array $attributes): array => [
            'status' => FulfillmentShipmentStatus::Shipped,
            'shipped_at' => now(),
        ]);
    }

    public function delivered(): static
    {
        return $this->withTracking()->state(fn (array $attributes): array => [
            'status' => FulfillmentShipmentStatus::Delivered,
            'shipped_at' => now()->subDay(),
            'delivered_at' => now(),
        ]);
    }
}


cmd: php artisan make:livewire Admin/Orders/Index --class --no-interaction && php artisan make:livewire Admin/Orders/Show --class --no-interaction && php artisan make:test --pest Admin/OrderManagementTest --no-interaction


output:
Chunk ID: dc78a4
Wall time: 0.5113 seconds
Process exited with code 0
Original token count: 68
Output:

   INFO  Livewire component [app/Livewire/Admin/Orders/Index.php] created successfully.

   INFO  Livewire component [app/Livewire/Admin/Orders/Show.php] created successfully.

   INFO  Test [tests/Feature/Admin/OrderManagementTest.php] created successfully.


command: php artisan make:livewire Admin/Orders/Index --class --no-interaction && php artisan make:livewire Admin/Orders/Show --class --no-interaction && php artisan make:test --pest Admin/OrderManagementTest --no-interaction

type: unknown

aggregated_output:
   INFO  Livewire component [app/Livewire/Admin/Orders/Index.php] created successfully.

   INFO  Livewire component [app/Livewire/Admin/Orders/Show.php] created successfully.

   INFO  Test [tests/Feature/Admin/OrderManagementTest.php] created successfully.


cmd: sed -n '1,160p' app/Livewire/Admin/Orders/Index.php


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


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


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


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

aggregated_output:
<?php

namespace App\Livewire\Admin\Orders;

use Livewire\Component;

class Index extends Component
{
    public function render()
    {
        return view('livewire.admin.orders.index');
    }
}


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

aggregated_output:
<?php

namespace App\Livewire\Admin\Orders;

use Livewire\Component;

class Show extends Component
{
    public function render()
    {
        return view('livewire.admin.orders.show');
    }
}


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

aggregated_output: {{-- Act only according to that maxim whereby you can, at the same time, will that it should become a universal law. - Immanuel Kant --}}


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

aggregated_output: {{-- He who is contented is rich. - Laozi --}}


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

namespace App\Livewire\Admin\Orders;

use Livewire\Component;

class Index extends Component
{
    public function render()
    {
        return view('livewire.admin.orders.index');
    }
}


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

namespace App\Livewire\Admin\Orders;

use Livewire\Component;

class Show extends Component
{
    public function render()
    {
        return view('livewire.admin.orders.show');
    }
}


output:
Chunk ID: 8ce2a6
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 16
Output:
<div>
    {{-- He who is contented is rich. - Laozi --}}
</div>


output:
Chunk ID: 1b0def
Wall time: 0.0000 seconds
Process exited with code 0
Original token count: 39
Output:
<div>
    {{-- Act only according to that maxim whereby you can, at the same time, will that it should become a universal law. - Immanuel Kant --}}
</div>


cmd: rg -n "current_store|StoreScope|store_id|admin" app bootstrap routes database -g '*.php'


cmd: sed -n '1,220p' app/Http/Middleware/ResolveStore.php


cmd: sed -n '1,220p' app/Http/Middleware/EnsureAdminUser.php


cmd: sed -n '1,220p' app/Models/Concerns/BelongsToStore.php && sed -n '1,160p' app/Models/Scopes/StoreScope.php


command: sed -n '1,220p' app/Http/Middleware/ResolveStore.php

aggregated_output:
<?php

namespace App\Http\Middleware;

use App\Enums\StoreStatus;
use App\Models\Store;
use App\Models\StoreDomain;
use Closure;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Cache;
use Symfony\Component\HttpFoundation\Response;

class ResolveStore
{
    /**
     * Handle an incoming request.
     *
     * @param  \Closure(\Illuminate\Http\Request): (\Symfony\Component\HttpFoundation\Response)  $next
     */
    public function handle(Request $request, Closure $next): Response
    {
        $store = $request->is('admin*')
            ? $this->resolveAdminStore($request)
            : $this->resolveStorefrontStore($request);

        abort_unless($store, 404);

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

        if (! $request->is('admin*') && $store->status === StoreStatus::Suspended) {
            abort(503);
        }

        if ($request->is('admin*') && $store->status === StoreStatus::Suspended && ! $request->isMethodSafe()) {
            abort(403);
        }

        return $next($request);
    }

    private function resolveStorefrontStore(Request $request): ?Store
    {
        $hostname = $request->getHost();
        $cacheKey = "store_domain:{$hostname}";

        $storeId = Cache::remember($cacheKey, now()->addMinutes(5), function () use ($hostname): ?int {
            return StoreDomain::query()
                ->where('hostname', $hostname)
                ->value('store_id');
        });

        return $storeId ? Store::query()->find($storeId) : null;
    }

    private function resolveAdminStore(Request $request): ?Store
    {
        $user = $request->user();

        if (! $user) {
            return null;
        }

        $storeId = $request->session()->get('current_store_id');

        if (! $storeId) {
            $storeId = $user->stores()->oldest('stores.id')->value('stores.id');

            if ($storeId) {
                $request->session()->put('current_store_id', $storeId);
            }
        }

        if (! $storeId || ! $user->stores()->whereKey($storeId)->exists()) {
            return null;
        }

        return Store::query()->find($storeId);
    }
}


command: sed -n '1,220p' app/Http/Middleware/EnsureAdminUser.php

aggregated_output: sed: app/Http/Middleware/EnsureAdminUser.php: No such file or directory

status: failed


command: sed -n '1,220p' app/Models/Concerns/BelongsToStore.php && sed -n '1,160p' app/Models/Scopes/StoreScope.php

StoreScope.php

aggregated_output:
<?php

namespace App\Models\Concerns;

use App\Models\Scopes\StoreScope;
use App\Models\Store;

trait BelongsToStore
{
    public static function bootBelongsToStore(): void
    {
        static::addGlobalScope(new StoreScope);

        static::creating(function (object $model): void {
            if ($model->store_id || ! app()->bound('current_store')) {
                return;
            }

            $store = app('current_store');

            if ($store instanceof Store) {
                $model->store_id = $store->getKey();
            }
        });
    }
}
<?php

namespace App\Models\Scopes;

use App\Models\Store;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Scope;

class StoreScope implements Scope
{
    public function apply(Builder $builder, Model $model): void
    {
        if (! app()->bound('current_store')) {
            return;
        }

        $store = app('current_store');

        if (! $store instanceof Store) {
            return;
        }

        $builder->where($model->qualifyColumn('store_id'), $store->getKey());
    }
}


command: rg -n "current_store|StoreScope|store_id|admin" app bootstrap routes database -g '*.php'

type: search

cmd: rg -n 'current_store|StoreScope|store_id|admin' app bootstrap routes database -g '*.php'

path: app

aggregated_output:
database/factories/ShippingZoneFactory.php:21:            'store_id' => Store::factory(),
routes/web.php:37:Route::livewire('admin/login', AdminLogin::class)
routes/web.php:39:    ->name('admin.login');
routes/web.php:41:Route::post('admin/logout', function () {
routes/web.php:47:    return redirect()->route('admin.login');
routes/web.php:48:})->middleware('auth')->name('admin.logout');
routes/web.php:50:Route::middleware(['auth', 'verified', 'admin'])->prefix('admin')->name('admin.')->group(function (): void {
routes/web.php:79:Route::redirect('dashboard', 'admin')
database/factories/ProductFactory.php:27:            'store_id' => Store::factory(),
bootstrap/app.php:26:        $middleware->appendToGroup('admin', [
database/factories/NavigationMenuFactory.php:24:            'store_id' => Store::factory(),
database/factories/StoreSettingsFactory.php:21:            'store_id' => Store::factory(),
database/factories/DiscountFactory.php:24:            'store_id' => Store::factory(),
database/factories/TaxSettingsFactory.php:22:            'store_id' => Store::factory(),
database/factories/InventoryItemFactory.php:26:            'store_id' => fn (array $attributes): mixed => ProductVariant::query()
database/factories/InventoryItemFactory.php:30:                ?->store_id ?? Store::factory(),
app/Support/HandleGenerator.php:29:            ->where('store_id', $storeId)
database/factories/PageFactory.php:25:            'store_id' => Store::factory(),
database/factories/CustomerFactory.php:21:            'store_id' => Store::factory(),
database/factories/CartFactory.php:23:            'store_id' => Store::factory(),
database/factories/OrderFactory.php:31:            'store_id' => Store::factory(),
database/factories/CheckoutFactory.php:24:            'store_id' => Store::factory(),
app/Models/Order.php:24:        'store_id',
database/factories/CollectionFactory.php:26:            'store_id' => Store::factory(),
database/factories/ThemeFactory.php:22:            'store_id' => Store::factory(),
app/Models/Concerns/BelongsToStore.php:5:use App\Models\Scopes\StoreScope;
app/Models/Concerns/BelongsToStore.php:12:        static::addGlobalScope(new StoreScope);
app/Models/Concerns/BelongsToStore.php:15:            if ($model->store_id || ! app()->bound('current_store')) {
app/Models/Concerns/BelongsToStore.php:19:            $store = app('current_store');
app/Models/Concerns/BelongsToStore.php:22:                $model->store_id = $store->getKey();
app/Auth/CustomerUserProvider.php:36:        $store = app()->bound('current_store') ? app('current_store') : null;
app/Auth/CustomerUserProvider.php:42:        $query->where('store_id', $store->getKey());
database/factories/StoreDomainFactory.php:22:            'store_id' => Store::factory(),
database/factories/StoreDomainFactory.php:30:    public function admin(): static
app/Models/NavigationItem.php:40:        static::addGlobalScope('current_store', function (Builder $builder): void {
app/Models/NavigationItem.php:41:            if (! app()->bound('current_store')) {
app/Models/NavigationItem.php:45:            $store = app('current_store');
app/Models/NavigationItem.php:54:                    ->where('store_id', $store->getKey());
app/Models/NavigationMenu.php:20:        'store_id',
app/Models/ProductOption.php:36:        static::addGlobalScope('current_store', function (Builder $builder): void {
app/Models/ProductOption.php:37:            if (! app()->bound('current_store')) {
app/Models/ProductOption.php:41:            $store = app('current_store');
app/Models/ProductOption.php:50:                    ->where('store_id', $store->getKey());
app/Services/VariantMatrixService.php:89:                    'store_id' => $product->store_id,
app/Services/VariantMatrixService.php:111:                'store_id' => $product->store_id,
app/Services/VariantMatrixService.php:183:                'store_id' => $product->store_id,
app/Services/VariantMatrixService.php:201:        return Store::query()->findOrFail($product->store_id);
app/Models/Scopes/StoreScope.php:10:class StoreScope implements Scope
app/Models/Scopes/StoreScope.php:14:        if (! app()->bound('current_store')) {
app/Models/Scopes/StoreScope.php:18:        $store = app('current_store');
app/Models/Scopes/StoreScope.php:24:        $builder->where($model->qualifyColumn('store_id'), $store->getKey());
app/Traits/ChecksStoreRole.php:54:        if (! app()->bound('current_store')) {
app/Traits/ChecksStoreRole.php:58:        $store = app('current_store');
app/Traits/ChecksStoreRole.php:66:            $storeId = $model->getAttribute('store_id');
app/Traits/ChecksStoreRole.php:71:        if (property_exists($model, 'store_id')) {
app/Traits/ChecksStoreRole.php:72:            return is_numeric($model->store_id) ? (int) $model->store_id : null;
app/Models/InventoryItem.php:23:        'store_id',
app/Models/InventoryItem.php:48:            if (! $item->store_id) {
app/Models/InventoryItem.php:49:                $item->store_id = $s…16703 chars truncated…create_pages_table.php:25:            $table->index('store_id');
database/migrations/2026_05_03_223841_create_pages_table.php:26:            $table->index(['store_id', 'status']);
database/migrations/2026_05_03_223824_create_themes_table.php:16:            $table->foreignId('store_id')->constrained()->cascadeOnDelete();
database/migrations/2026_05_03_223824_create_themes_table.php:23:            $table->index('store_id');
database/migrations/2026_05_03_223824_create_themes_table.php:24:            $table->index(['store_id', 'status']);
database/migrations/2026_05_03_211425_create_store_users_table.php:15:            $table->foreignId('store_id')->constrained()->cascadeOnDelete();
database/migrations/2026_05_03_211425_create_store_users_table.php:17:            $table->enum('role', ['owner', 'admin', 'staff', 'support'])->default('staff');
database/migrations/2026_05_03_211425_create_store_users_table.php:20:            $table->primary(['store_id', 'user_id']);
database/migrations/2026_05_03_211425_create_store_users_table.php:22:            $table->index(['store_id', 'role']);
database/migrations/2026_05_03_211416_create_store_domains_table.php:16:            $table->foreignId('store_id')->constrained()->cascadeOnDelete();
database/migrations/2026_05_03_211416_create_store_domains_table.php:18:            $table->enum('type', ['storefront', 'admin', 'api'])->default('storefront');
database/migrations/2026_05_03_211416_create_store_domains_table.php:23:            $table->index('store_id');
database/migrations/2026_05_03_211416_create_store_domains_table.php:24:            $table->index(['store_id', 'is_primary']);
database/migrations/2026_05_03_225413_create_shipping_zones_table.php:16:            $table->foreignId('store_id')->constrained()->cascadeOnDelete();
database/migrations/2026_05_03_225413_create_shipping_zones_table.php:21:            $table->index('store_id');
database/migrations/2026_05_03_225422_create_tax_settings_table.php:15:            $table->foreignId('store_id')->primary()->constrained()->cascadeOnDelete();
app/Providers/AppServiceProvider.php:82:            if ($request->is('admin*')) {
app/Providers/AppServiceProvider.php:83:                return route('admin.login');
app/Providers/AppServiceProvider.php:97:            $store = app()->bound('current_store') ? app('current_store') : null;
database/migrations/2026_05_03_225427_create_discounts_table.php:16:            $table->foreignId('store_id')->constrained()->cascadeOnDelete();
database/migrations/2026_05_03_225427_create_discounts_table.php:29:            $table->unique(['store_id', 'code']);
database/migrations/2026_05_03_225427_create_discounts_table.php:30:            $table->index('store_id');
database/migrations/2026_05_03_225427_create_discounts_table.php:31:            $table->index(['store_id', 'status']);
database/migrations/2026_05_03_225427_create_discounts_table.php:32:            $table->index(['store_id', 'type']);
database/migrations/2026_05_03_211556_create_customers_table.php:16:            $table->foreignId('store_id')->constrained()->cascadeOnDelete();
database/migrations/2026_05_03_211556_create_customers_table.php:23:            $table->unique(['store_id', 'email']);
database/migrations/2026_05_03_211556_create_customers_table.php:24:            $table->index('store_id');
database/migrations/2026_05_03_223844_create_navigation_menus_table.php:16:            $table->foreignId('store_id')->constrained()->cascadeOnDelete();
database/migrations/2026_05_03_223844_create_navigation_menus_table.php:21:            $table->unique(['store_id', 'handle']);
database/migrations/2026_05_03_223844_create_navigation_menus_table.php:22:            $table->index('store_id');
database/migrations/2026_05_03_213856_create_products_table.php:16:            $table->foreignId('store_id')->constrained()->cascadeOnDelete();
database/migrations/2026_05_03_213856_create_products_table.php:27:            $table->unique(['store_id', 'handle']);
database/migrations/2026_05_03_213856_create_products_table.php:28:            $table->index('store_id');
database/migrations/2026_05_03_213856_create_products_table.php:29:            $table->index(['store_id', 'status']);
database/migrations/2026_05_03_213856_create_products_table.php:30:            $table->index(['store_id', 'published_at']);
database/migrations/2026_05_03_213856_create_products_table.php:31:            $table->index(['store_id', 'vendor']);
database/migrations/2026_05_03_213856_create_products_table.php:32:            $table->index(['store_id', 'product_type']);
database/migrations/2026_05_03_211419_create_store_settings_table.php:15:            $table->foreignId('store_id')->primary()->constrained()->cascadeOnDelete();
database/migrations/2026_05_03_213901_create_inventory_items_table.php:16:            $table->foreignId('store_id')->constrained()->cascadeOnDelete();
database/migrations/2026_05_03_213901_create_inventory_items_table.php:22:            $table->index('store_id');