Closure, 'after' => * Closure]`. That file is yours — never touched by the generator. */ function productTestContext(string $when): void { $file = base_path('tests/Context/product.php'); if (! is_file($file)) { return; } /** @var Closure(): void|array{before?: Closure(): void, after?: Closure(): void} $hooks */ $hooks = require $file; $hook = $hooks instanceof Closure ? ($when === 'before' ? $hooks : null) : ($hooks[$when] ?? null); if ($hook instanceof Closure) { $hook(); } } beforeEach(function () { resetRbac(); Storage::fake('local'); productTestContext('before'); }); afterEach(fn () => productTestContext('after')); // This module's tests: `pest --group=product` runs them alone, and // `pest --mutate` on this file scores them against the module's own classes // (by path: a group still loads every other module's mutates()). pest()->group('product'); mutates( 'App\Actions\Product\BulkDeleteProducts', 'App\Actions\Product\BulkForceDeleteProducts', 'App\Actions\Product\BulkRestoreProducts', 'App\Actions\Product\BulkUpdateProductStatus', 'App\Actions\Product\DeleteProduct', 'App\Actions\Product\ForceDeleteProduct', 'App\Actions\Product\RestoreProduct', 'App\Actions\Product\StoreProduct', 'App\Actions\Product\UpdateProduct', 'App\Http\Controllers\Api\ProductApiController', 'App\Http\Controllers\Api\ProductFileApiController', 'App\Http\Controllers\Product\ProductBulkController', 'App\Http\Controllers\Product\ProductBulkForceDeleteController', 'App\Http\Controllers\Product\ProductBulkRestoreController', 'App\Http\Controllers\Product\ProductBulkStatusController', 'App\Http\Controllers\Product\ProductController', 'App\Http\Controllers\Product\ProductExcelExportController', 'App\Http\Controllers\Product\ProductExportController', 'App\Http\Controllers\Product\ProductFileController', 'App\Http\Controllers\Product\ProductFormController', 'App\Http\Controllers\Product\ProductImportController', 'App\Http\Controllers\Product\ProductImportPreviewController', 'App\Http\Controllers\Product\ProductLookupController', 'App\Http\Controllers\Product\ProductRestoreController', 'App\Http\Controllers\Product\ProductReviewController', 'App\Http\Controllers\Product\ProductTrashController', 'App\Http\Controllers\Product\ProductProductVariantController', 'App\Http\Requests\Product\BulkDestroyProductRequest', 'App\Http\Requests\Product\BulkForceDeleteProductRequest', 'App\Http\Requests\Product\BulkProductRequest', 'App\Http\Requests\Product\BulkRestoreProductRequest', 'App\Http\Requests\Product\BulkStatusProductRequest', 'App\Http\Requests\Product\ImportProductRequest', 'App\Http\Requests\Product\ProductRequest', 'App\Http\Requests\Product\StoreProductRequest', 'App\Http\Requests\Product\UpdateProductRequest', 'App\Policies\ProductPolicy', ); /** * A valid store/update payload, overridable per-test. * * The generic values below satisfy the schema. A module with business rules * the schema cannot state (an asset must be `aktif`, a destination must differ * from the origin) owns `tests/Payloads/product.php`: an array merged over * the base, or a `Closure(array $base): array`. That file is yours — never * touched by the generator — so the rules and this test stay in step across * `--force`. * * @param array $overrides * @return array */ function productPayload(array $overrides = []): array { $base = [ 'category_id' => Category::query()->where('level', 'category')->value('id') ?? Category::factory()->create(['level' => 'category', 'parent_id' => Category::factory()])->id, 'name' => 'Sample Name', 'slug' => 'ref-'.fake()->unique()->numerify('#####'), 'sku' => 'REF-'.fake()->unique()->numerify('#####'), 'status' => 'draft', 'price' => 5.5, 'compare_at_price' => 5.5, 'cost_price' => 5.5, 'photos_new' => [UploadedFile::fake()->image('a.jpg'), UploadedFile::fake()->image('b.jpg')], 'video_url' => 'https://youtu.be/dQw4w9WgXcQ', 'description' => 'Some descriptive text.', 'size_chart' => UploadedFile::fake()->create('size_chart.pdf', 100), 'is_featured' => true, 'published_at' => '2026-01-15', 'published_by' => User::query()->value('id'), 'specs' => ['Colour' => 'Blue', 'Material' => 'Cotton'], ]; $domain = base_path('tests/Payloads/product.php'); if (is_file($domain)) { /** @var array|Closure(array): array $rules */ $rules = require $domain; $base = $rules instanceof Closure ? $rules($base) : array_merge($base, $rules); } return array_merge($base, $overrides); } /** * The payload an edit sends: what is fixed once created stays out, as the * edit form leaves it out. * * @param array $overrides * @return array */ function productUpdatePayload(array $overrides = []): array { return array_diff_key(productPayload($overrides), array_flip(['sku'])); } // Every count in this file starts from an empty table: rows a migration // inserts are named here once, instead of as a count off by them in each test. it('starts from an empty products table', function () { $rows = DB::table('products')->count(); expect($rows)->toBe(0, "products holds {$rows} rows before any test made one: rows a migration inserts belong in a seeder (database/seeders)."); }); describe('authorization', function () { it('redirects guests to login', function () { get(route('product.index'))->assertRedirect(route('login')); }); it('allows users with product.view to see the index', function () { actingAs(userCan(['product.view', 'product.export'])); get(route('product.index')) ->assertOk() ->assertInertia(fn (Assert $page) => $page ->component('product/index') ->has('items.data') ->has('total') ->has('filters.per_page') ->has('filters.search') ->has('fkOptionsUrl') ->has('realtimeChannel') ->has('savedViews') ->has('stats') // What the page may offer, asked of the policy for this user. ->where('abilities.export', true) ->where('abilities.create', false) ->where('abilities.import', false) ->where('abilities.update', false) ->where('abilities.updateRestricted', false) ->where('abilities.delete', false) ->where('abilities.restore', false) ->where('abilities.forceDelete', false)); }); it('allows users with product.view to see the detail page', function () { $product = Product::factory()->create(['description' => '

One.

Two.

', 'published_by' => User::factory(), 'category_id' => Category::factory(['level' => 'category', 'parent_id' => Category::factory()])]); actingAs(userCan(['product.view'])); get(route('product.show', $product)) ->assertOk() ->assertInertia(fn (Assert $page) => $page ->component('product/show') ->where('item.id', $product->id) ->has('item.category') ->has('item.category_id') ->has('item.name') ->has('item.slug') ->has('item.sku') ->has('item.status') ->has('item.price') ->has('item.compare_at_price') ->has('item.cost_price') ->has('item.photos') ->has('item.video_url') ->has('item.description') ->has('item.size_chart') ->has('item.is_featured') ->has('item.published_at') ->has('item.published_by') ->has('item.specs') ->has('item.created_at') ->has('item.updated_at') ->where('item.publishedByRef', User::query()->find($product->published_by)?->name) ->has('fkOptionsUrl') ->where('abilities.update', false) ->where('abilities.updateRestricted', false) ->where('abilities.delete', false) // The audit rail is the super-admin's alone. ->where('timeline', null)); actingAs(makeSuperAdmin()); get(route('product.show', $product)) ->assertInertia(fn (Assert $page) => $page ->where('abilities.update', true) ->where('abilities.updateRestricted', true) ->where('abilities.delete', true)); }); it('shows the newest ten related rows of each panel, with their columns', function () { $product = Product::factory()->create(); $productVariants = ProductVariant::factory()->count(11)->create(['product_id' => $product->getKey()]); $reviews = Review::factory()->count(11)->create(['product_id' => $product->getKey(), 'customer_id' => Customer::factory()->create()->id]); $coupons = Coupon::factory()->count(11)->create(['applies_to_type' => $product->getMorphClass(), 'applies_to_id' => $product->getKey()]); $tags = Tag::factory()->count(11)->create(); $product->tags()->attach($tags->modelKeys()); actingAs(userCan(['product.view'])); get(route('product.show', $product)) ->assertOk() ->assertInertia(fn (Assert $page) => $page ->has('item.productVariants', 10) ->where('item.productVariants.0', json_decode((string) json_encode($productVariants->sortByDesc('id')->first()?->only(['id', 'name', 'sku', 'size', 'color', 'price', 'stock'])), true)) ->has('item.reviews', 10) ->where('item.reviews.0', json_decode((string) json_encode([...($reviews->sortByDesc('id')->first()?->only(['id', 'title', 'rating', 'status']) ?? []), 'customer' => DB::table('customers')->where('id', $reviews->sortByDesc('id')->first()?->customer_id)->value('name')]), true)) ->has('item.coupons', 10) ->where('item.coupons.0', json_decode((string) json_encode($coupons->sortByDesc('id')->first()?->only(['id', 'code', 'description', 'kind', 'percent_off', 'amount_off', 'starts_on'])), true)) ->has('item.tags', 10) ->where('item.tags.0', fn ($row): bool => $row->all() === $tags->firstWhere('id', $row['id'])?->only(['id', 'name']))); }); it('exports a CSV for a user with product.export', function () { Product::factory()->count(3)->create(); actingAs(userCan(['product.export'])); $response = get(route('product.export')); $response->assertOk(); expect($response->headers->get('content-type'))->toContain('text/csv'); }); it('exports an .xlsx spreadsheet for a user with product.export', function () { Product::factory()->count(2)->create(); actingAs(userCan(['product.export'])); $response = get(route('product.export-excel')); $response->assertOk(); expect($response->headers->get('content-type'))->toContain('spreadsheet'); }); it('records who exported, and how much', function () { Product::factory()->count(3)->create(); actingAs(userCan(['product.export'])); get(route('product.export'))->assertOk(); // Who took a copy, when, and how much of it. $entry = App\Models\Activity::where('event', 'exported')->latest('id')->first(); expect($entry)->not->toBeNull() ->and($entry->properties['rows'])->toBe(3) ->and($entry->properties['module'])->toBe('product'); }); it('lets a super-admin bypass every guard', function () { actingAs(makeSuperAdmin()); get(route('product.index'))->assertOk(); }); }); describe('permissions', function () { // Each route answers to one permission of this module: a user holding // every other one is refused. What a holder may do is tested below. it('refuses :dataset without the permission it answers to', function (string $method, string $name, bool $record, string $permission, array $parameters = []) { actingAs(userCan(array_values(array_diff(['product.view', 'product.create', 'product.edit', 'product.delete', 'product.export', 'product.restore', 'product.force-delete', 'product.import', 'product.edit-restricted'], [$permission])))); if ($record) { $parameters = [Product::factory()->create(), ...$parameters]; } $this->call($method, route("product.{$name}", $parameters))->assertForbidden(); })->with([ 'the list' => ['GET', 'index', false, 'product.view'], 'a record' => ['GET', 'show', true, 'product.view'], 'the record the form opens with' => ['GET', 'form-data', true, 'product.view'], 'the CSV export' => ['GET', 'export', false, 'product.export'], 'the Excel export' => ['GET', 'export-excel', false, 'product.export'], 'a new record' => ['POST', 'store', false, 'product.create'], 'a change' => ['PUT', 'update', true, 'product.edit'], 'a delete' => ['DELETE', 'destroy', true, 'product.delete'], 'a selection deleted' => ['POST', 'bulk-destroy', false, 'product.delete'], 'the import template' => ['GET', 'import-template', false, 'product.import'], 'an import' => ['POST', 'import', false, 'product.import'], 'an import dry run' => ['POST', 'import-preview', false, 'product.import'], 'a selection moved to a status' => ['POST', 'bulk-status', false, 'product.edit'], 'a record restored' => ['PATCH', 'restore', true, 'product.restore'], 'a record deleted for good' => ['DELETE', 'force-delete', true, 'product.force-delete'], 'a selection restored' => ['POST', 'bulk-restore', false, 'product.restore'], 'a selection deleted for good' => ['POST', 'bulk-force-delete', false, 'product.force-delete'], 'a picker search' => ['GET', 'fk-options', false, 'product.view'], 'an uploaded file' => ['GET', 'file', true, 'product.view', ['column' => 'photos']], ]); }); describe('store', function () { it('creates a record and logs the activity', function () { actingAs(userCan(['product.create'])); $payload = productPayload(); post(route('product.store'), $payload) ->assertRedirect() ->assertSessionHasNoErrors() ->assertInertiaFlash('toast', ['type' => 'success', 'message' => __('crud.created')]); expect(Product::count())->toBe(1); $product = Product::query()->firstOrFail(); expect($product->name)->toBe($payload['name']); assertDatabaseHas('activity_log', ['subject_type' => Product::class, 'subject_id' => $product->getKey(), 'event' => 'created']); }); it('refuses :dataset', function (string $field, mixed $value, ?string $error = null) { actingAs(userCan(['product.create', 'tag.create'])); // A value another record must hold first is made here, not up front. $value = $value instanceof Closure ? $value() : $value; post(route('product.store'), productPayload([$field => $value])) ->assertSessionHasErrors($error ?? $field); })->with([ 'a blank category_id' => ['category_id', ''], 'a category_id that names nothing' => ['category_id', 999999], 'a category_id that is not a number' => ['category_id', 'not-a-number'], 'a blank name' => ['name', ''], 'a name that is not text' => ['name', ['not', 'text']], 'a name past 120 characters' => ['name', str_repeat('a', 121)], 'a blank status' => ['status', ''], 'a status outside its cases' => ['status', 'not-a-case'], 'a compare_at_price that is not a number' => ['compare_at_price', 'not-a-number'], 'a negative compare_at_price' => ['compare_at_price', -1], 'a cost_price that is not a number' => ['cost_price', 'not-a-number'], 'a negative cost_price' => ['cost_price', -1], 'a blank is_featured' => ['is_featured', ''], 'an is_featured that is neither true nor false' => ['is_featured', 'maybe'], 'a size_chart of a type it does not take' => ['size_chart', fn () => UploadedFile::fake()->create('program.exe', 10, 'application/x-msdownload')], 'a size_chart whose name hides another type' => ['size_chart', fn () => UploadedFile::fake()->create('report.pdf.exe', 10, 'application/pdf')], 'a size_chart past 5120 KB' => ['size_chart', fn () => UploadedFile::fake()->create('heavy.pdf', 5121, 'application/pdf')], 'tag_ids that is not a list' => ['tag_ids', 'not-a-list'], 'a tag_ids entry that names nothing' => ['tag_ids', [999999], 'tag_ids.0'], 'a tag_ids entry that is not a number' => ['tag_ids', ['not-a-number'], 'tag_ids.0'], 'a slug that is not text' => ['slug', ['not', 'text']], 'a slug past 140 characters' => ['slug', str_repeat('a', 141)], 'a compare_at_price above 99999999.99' => ['compare_at_price', '100000000'], 'a cost_price above 99999999.99' => ['cost_price', '100000000'], 'a description that is not text' => ['description', ['not', 'text']], 'a description past 2000 characters' => ['description', str_repeat('a', 2001)], 'photos_existing that is not a list' => ['photos_existing', 'not-a-list'], 'a photos_existing entry that is not text' => ['photos_existing', [['not', 'text']], 'photos_existing.0'], 'photos_new that is not a list' => ['photos_new', 'not-a-list'], 'more than 20 photos_new' => ['photos_new', array_fill(0, 21, 'x')], 'a photos_new entry that is not an image' => ['photos_new', fn () => [UploadedFile::fake()->create('notes.pdf', 10, 'application/pdf')], 'photos_new.0'], 'a photos_new entry wider than 8000 pixels' => ['photos_new', fn () => [UploadedFile::fake()->image('wide.jpg', 8001, 1)], 'photos_new.0'], 'a photos_new entry past 5120 KB' => ['photos_new', fn () => [UploadedFile::fake()->image('heavy.jpg')->size(5121)], 'photos_new.0'], 'tag_new that is not a list' => ['tag_new', 'not-a-list'], 'a tag_new entry that is not text' => ['tag_new', [['not', 'text']], 'tag_new.0'], 'a tag_new entry past 255 characters' => ['tag_new', [str_repeat('a', 256)], 'tag_new.0'], 'more than 100 specs pairs' => ['specs', array_fill_keys(array_map(fn (int $i): string => 'key'.$i, range(1, 101)), 'value')], 'a specs key past 100 characters' => ['specs', [str_repeat('k', 101) => 'value']], 'a specs value past 1000 characters' => ['specs', ['key' => str_repeat('a', 1001)], 'specs.key'], 'a sku that is not text' => ['sku', ['not', 'text']], 'a sku past 32 characters' => ['sku', str_repeat('a', 33)], ]); it('refuses a store that leaves out :dataset', function (string $field) { actingAs(userCan(['product.create'])); post(route('product.store'), array_diff_key(productPayload(), [$field => true])) ->assertSessionHasErrors($field); })->with(['category_id', 'name', 'status', 'is_featured', 'sku']); it('accepts :dataset left empty', function (string $field) { actingAs(userCan(['product.create', 'tag.create'])); post(route('product.store'), productPayload([$field => null])) ->assertSessionDoesntHaveErrors($field); })->with(['slug', 'compare_at_price', 'cost_price', 'video_url', 'description', 'specs', 'size_chart', 'tag_ids', 'photos_existing', 'photos_new', 'tag_new']); it('names the trash when a deleted record holds the :dataset', function (string $column) { actingAs(userCan(['product.create'])); $held = Product::factory()->create(); $held->delete(); $value = (string) $held->getAttribute($column); post(route('product.store'), productPayload([$column => $held->getAttribute($column)])) ->assertSessionHasErrors([$column => __('validation.taken_by_trashed', ['attribute' => __("validation.attributes.{$column}"), 'value' => $value])]); })->with(['sku']); it('refuses a number its column cannot hold', function () { actingAs(userCan(['product.create'])); post(route('product.store'), productPayload(['price' => '1.111'])) ->assertSessionHasErrors('price'); post(route('product.store'), productPayload(['compare_at_price' => '1.111'])) ->assertSessionHasErrors('compare_at_price'); }); it('creates a new tags tag on the fly for a holder of tag.create', function () { actingAs(userCan(['product.create', 'tag.create'])); post(route('product.store'), productPayload(['tag_new' => ['Fresh Tag XYZ']])) ->assertRedirect(); assertDatabaseHas('tags', ['name' => 'Fresh Tag XYZ']); expect(Product::latest('id')->first()->tags()->where('name', 'Fresh Tag XYZ')->exists())->toBeTrue(); // Made as its own module makes a row: in the audit trail. assertDatabaseHas('activity_log', ['subject_type' => Tag::class, 'event' => 'created']); }); // A typed-in name is a row in another module, so it needs that // module's permission, not only this one's. it('refuses a new tags tag without tag.create', function () { actingAs(userCan(['product.create'])); post(route('product.store'), productPayload(['tag_new' => ['Fresh Tag XYZ']])) ->assertSessionHasErrors('tag_new'); assertDatabaseMissing('tags', ['name' => 'Fresh Tag XYZ']); }); it('keeps the formatting of description and drops what could run', function () { actingAs(userCan(['product.create'])); $html = '

Kept bold

link'; post(route('product.store'), productPayload(['description' => $html])) ->assertSessionHasNoErrors(); $product = Product::query()->firstOrFail(); expect((string) $product->getRawOriginal('description')) ->toContain('

Kept bold

') ->not->toContain('onerror') ->not->toContain('not->toContain('javascript:'); // A row written around the model is cleaned when it is read. Product::query()->whereKey($product->getKey())->update(['description' => $html]); expect((string) $product->refresh()->description)->not->toContain('onerror')->not->toContain('create(); $original = $product->name; // A minute on, so the save moves the timestamp the trail must leave out. $this->travel(1)->minutes(); put(route('product.update', $product), productUpdatePayload(['name' => 'Renamed Value'])) ->assertRedirect() ->assertSessionHasNoErrors() ->assertInertiaFlash('toast', ['type' => 'success', 'message' => __('crud.updated')]); expect($product->refresh()->name)->toBe('Renamed Value'); // One entry: what the field held, what it holds now, and not the timestamp. $entry = App\Models\Activity::where('event', 'updated')->where('subject_type', Product::class) ->where('subject_id', $product->getKey())->latest('id')->firstOrFail(); expect($entry->attribute_changes['old']['name'])->toBe($original) ->and($entry->attribute_changes['attributes']['name'])->toBe('Renamed Value') ->and($entry->attribute_changes['attributes'])->not->toHaveKey('updated_at'); }); }); describe('fixed once created', function () { it('refuses an edit that changes sku, and takes it sent back as it is', function () { actingAs(userCan(['product.edit'])); $product = Product::factory()->create(); put(route('product.update', $product), [...productUpdatePayload(), 'sku' => 'Changed']) ->assertSessionHasErrors('sku'); put(route('product.update', $product), [...productUpdatePayload(), 'sku' => $product->getRawOriginal('sku')]) ->assertSessionDoesntHaveErrors('sku'); }); }); describe('as the record stands', function () { it('records an edit from the record as it stands, not as it was read', function () { $product = Product::factory()->create(); Product::query()->whereKey($product->getKey())->update(['name' => 'Meanwhile']); app(UpdateProduct::class)->handle($product, ['name' => 'Renamed Value']); $entry = App\Models\Activity::where('event', 'updated')->where('subject_type', Product::class) ->where('subject_id', $product->getKey())->latest('id')->firstOrFail(); expect($entry->attribute_changes['old']['name'])->toBe('Meanwhile'); }); it('names a deleted record as it stands, not as it was read', function () { $product = Product::factory()->create(); Product::query()->whereKey($product->getKey())->update(['name' => 'Meanwhile']); app(DeleteProduct::class)->handle($product); expect(App\Models\Activity::where('event', 'deleted')->where('subject_type', Product::class) ->where('subject_id', $product->getKey())->latest('id')->firstOrFail()->description)->toContain('Meanwhile'); }); }); describe('form data', function () { it('returns the record the modal opens with', function () { $product = Product::factory()->create(['description' => '

One.

Two.

', 'published_by' => User::factory(), 'category_id' => Category::factory(['level' => 'category', 'parent_id' => Category::factory()])]); $picked0 = Tag::factory()->create(); $product->tags()->attach($picked0); actingAs(userCan(['product.view'])); get(route('product.form-data', $product)) ->assertOk() ->assertJsonFragment(['id' => $product->id]) ->assertJsonPath('name', $product->name) ->assertJsonPath('id', $product->id) ->assertJsonPath('category_id', $product->category_id) ->assertJsonPath('description', '

One.

Two.

') ->assertJsonPath('published_by', $product->published_by) ->assertJsonPath('specs', $product->specs) ->assertJsonPath('categoryChain.categories_category.id', $product->category_id) ->assertJsonPath('categoryChain.categories_category.label', fn (string $label): bool => str_contains($label, (string) Category::query()->find($product->category_id)?->name)) ->assertJsonPath('tag_ids', [$picked0->id]); }); it('strips what a duplicate must not carry over', function () { $product = Product::factory()->create(); actingAs(userCan(['product.view', 'product.create'])); // Identity, unique columns and uploads belong to the source record. $payload = get(route('product.form-data', [$product, 'duplicate' => 1])) ->assertOk() ->json(); expect($payload)->not->toHaveKey('id') ->and(array_intersect_key($payload, array_flip(['slug', 'sku', 'photos', 'size_chart', 'created_at'])))->toBe([]); }); it('refuses a copy to a viewer who may not create', function () { $product = Product::factory()->create(); actingAs(userCan(['product.view'])); get(route('product.form-data', [$product, 'duplicate' => 1]))->assertForbidden(); }); }); describe('saved views', function () { it('stores a filter preset scoped to this module', function () { $user = userCan(['product.view']); actingAs($user); post(route('user-views.store'), [ 'module' => 'product', 'name' => 'My preset', 'filters' => ['search' => 'x'], ]); assertDatabaseHas('user_views', [ 'module' => 'product', 'name' => 'My preset', 'user_id' => $user->id, ]); }); it('hands the index the presets of this user, by name', function () { actingAs(userCan(['product.view'])); post(route('user-views.store'), ['module' => 'product', 'name' => 'Second', 'filters' => ['search' => 'b']]); post(route('user-views.store'), ['module' => 'product', 'name' => 'First', 'filters' => ['search' => 'a']]); get(route('product.index')) ->assertInertia(fn (Assert $page) => $page ->has('savedViews', 2) ->has('savedViews.0.id') ->where('savedViews.0.name', 'First') ->where('savedViews.0.filters', ['search' => 'a'])); }); }); describe('restricted fields', function () { it('ignores restricted-field changes without product.edit-restricted', function () { $product = Product::factory()->create(['price' => '12']); actingAs(userCan(['product.edit'])); put(route('product.update', $product), productUpdatePayload(['price' => '99'])) ->assertRedirect(); assertDatabaseHas('products', ['id' => $product->id, 'price' => '12']); }); it('applies restricted-field changes with product.edit-restricted', function () { $product = Product::factory()->create(['price' => '12']); actingAs(userCan(['product.edit', 'product.edit-restricted'])); put(route('product.update', $product), productUpdatePayload(['price' => '99'])) ->assertRedirect(); assertDatabaseHas('products', ['id' => $product->id, 'price' => '99']); }); it('keeps a restricted field an API edit sends without product.edit-restricted, and takes it with', function () { $product = Product::factory()->create(['price' => '12']); Sanctum::actingAs(userCan(['product.view', 'product.edit']), ['*']); patchJson("/api/v1/products/{$product->id}", ['price' => '99'])->assertOk(); assertDatabaseHas('products', ['id' => $product->id, 'price' => '12']); Sanctum::actingAs(userCan(['product.view', 'product.edit', 'product.edit-restricted']), ['*']); patchJson("/api/v1/products/{$product->id}", ['price' => '99'])->assertOk(); assertDatabaseHas('products', ['id' => $product->id, 'price' => '99']); }); }); describe('multi-file gallery', function () { it('stores every uploaded photos on create', function () { actingAs(userCan(['product.create'])); post(route('product.store'), productPayload()) ->assertRedirect(); $product = Product::latest('id')->first(); expect($product->photos)->toHaveCount(2); Storage::disk('local')->assertExists($product->photos[0]); }); it('serves a stored photos only through the record, and only a path the record holds', function () { actingAs(userCan(['product.create', 'product.view'])); post(route('product.store'), productPayload()) ->assertRedirect(); $product = Product::latest('id')->first(); get(route('product.file', ['product' => $product->id, 'column' => 'photos', 'path' => $product->photos[0]])) ->assertOk(); get(route('product.file', ['product' => $product->id, 'column' => 'photos', 'path' => 'products/not-this-record.jpg'])) ->assertNotFound(); get(route('product.file', ['product' => $product->id, 'column' => 'not_a_file_column'])) ->assertNotFound(); }); it('keeps chosen existing photos and appends new ones on update', function () { Storage::disk('local')->put('products/keep.jpg', 'kept'); Storage::disk('local')->put('products/drop.jpg', 'dropped'); $product = Product::factory()->create(['photos' => ['products/keep.jpg', 'products/drop.jpg']]); actingAs(userCan(['product.edit'])); put(route('product.update', $product), productUpdatePayload([ // A path this record does not hold is not taken over from the form. 'photos_existing' => ['products/elsewhere.jpg', 'products/keep.jpg'], 'photos_new' => [UploadedFile::fake()->image('added.jpg')], ]))->assertRedirect(); $product->refresh(); expect($product->photos)->toHaveCount(2) ->and($product->photos[0])->toBe('products/keep.jpg') ->and($product->photos)->not->toContain('products/drop.jpg') ->and($product->photos)->not->toContain('products/elsewhere.jpg'); // The file the save let go of is deleted once the save is in. Storage::disk('local')->assertMissing('products/drop.jpg'); Storage::disk('local')->assertExists('products/keep.jpg'); // The trail reads the list as a list, and not the timestamp beside it. $entry = Activity::query()->where('subject_type', Product::class)->where('subject_id', $product->id)->where('event', 'updated')->latest('id')->firstOrFail(); expect($entry->attribute_changes['attributes']['photos'])->toBe($product->photos) ->and($entry->attribute_changes['attributes'])->not->toHaveKey('updated_at'); }); }); describe('image sizes', function () { it('queues the sizes of an uploaded photos', function () { Queue::fake(); actingAs(userCan(['product.create'])); post(route('product.store'), productPayload())->assertRedirect(); $stored = (array) Product::latest('id')->firstOrFail()->photos; expect($stored)->not->toBeEmpty(); Queue::assertPushed(MakeImageVariants::class, fn (MakeImageVariants $job): bool => in_array($job->path, $stored, true) && $job->sizes === Product::IMAGE_VARIANTS['photos']); }); it('writes each size as WebP, no larger than the size, the shape kept and never enlarged', function () { $sizes = Product::IMAGE_VARIANTS['photos']; $wide = max($sizes) + 10; Storage::disk('local')->put('products/wide.png', ImageFixtures::png($wide, intdiv($wide, 2))); Storage::disk('local')->put('products/small.png', ImageFixtures::png(20, 10)); (new MakeImageVariants('products/wide.png', $sizes))->handle(); (new MakeImageVariants('products/small.png', $sizes))->handle(); foreach ($sizes as $size => $edge) { $made = (array) getimagesizefromstring((string) Storage::disk('local')->get(ImageVariants::path('products/wide.png', $size))); expect($made['mime'])->toBe('image/webp') ->and($made[0])->toBe($edge) ->and(abs($made[1] - $edge / 2))->toBeLessThanOrEqual(1); $kept = (array) getimagesizefromstring((string) Storage::disk('local')->get(ImageVariants::path('products/small.png', $size))); expect([$kept[0], $kept[1]])->toBe([20, 10]); } }); it('turns a phone photo upright before it is sized', function () { Storage::disk('local')->put('products/phone.jpg', ImageFixtures::jpegWithOrientation(40, 20, 6)); (new MakeImageVariants('products/phone.jpg', Product::IMAGE_VARIANTS['photos']))->handle(); $made = (array) getimagesizefromstring((string) Storage::disk('local')->get(ImageVariants::path('products/phone.jpg', 'thumb'))); expect([$made[0], $made[1]])->toBe([20, 40]); }); it('takes the sizes away with the image, replaced or deleted', function () { $sizes = Product::IMAGE_VARIANTS['photos']; foreach (['old', 'new'] as $name) { Storage::disk('local')->put("products/{$name}.png", ImageFixtures::png(64, 32)); (new MakeImageVariants("products/{$name}.png", $sizes))->handle(); } $product = Product::factory()->create(['photos' => ['products/old.png']]); $product->update(['photos' => ['products/new.png']]); foreach (array_keys($sizes) as $size) { Storage::disk('local')->assertMissing(ImageVariants::path('products/old.png', $size)); Storage::disk('local')->assertExists(ImageVariants::path('products/new.png', $size)); } $product->forceDelete(); foreach (array_keys($sizes) as $size) { Storage::disk('local')->assertMissing(ImageVariants::path('products/new.png', $size)); } }); it('serves a size once it is built, and the original until then', function () { actingAs(userCan(['product.view'])); Storage::disk('local')->put('products/served.png', ImageFixtures::png(64, 32)); // Queued, not run: nothing is built yet. Queue::fake(); $product = Product::factory()->create(['photos' => ['products/served.png']]); $url = route('product.file', ['product' => $product->id, 'column' => 'photos', 'path' => 'products/served.png', 'size' => 'thumb']); $before = get($url)->assertOk(); expect($before->headers->get('Content-Type'))->toBe('image/png') ->and((string) $before->headers->get('Cache-Control'))->toContain('max-age='.ImageVariants::PENDING_MAX_AGE); (new MakeImageVariants('products/served.png', Product::IMAGE_VARIANTS['photos']))->handle(); $after = get($url)->assertOk(); expect($after->headers->get('Content-Type'))->toBe('image/webp') ->and((string) $after->headers->get('Cache-Control'))->toContain('max-age='.ImageVariants::BUILT_MAX_AGE); }); it('refuses a size the column does not keep', function () { actingAs(userCan(['product.view'])); Queue::fake(); Storage::disk('local')->put('products/served.png', ImageFixtures::png(64, 32)); $product = Product::factory()->create(['photos' => ['products/served.png']]); get(route('product.file', ['product' => $product->id, 'column' => 'photos', 'path' => 'products/served.png', 'size' => 'nosuchsize'])) ->assertStatus(400); }); }); describe('uploads', function () { it('stores the size_chart sent with a new record, and swaps it on edit', function () { actingAs(userCan(['product.create', 'product.edit'])); post(route('product.store'), productPayload())->assertSessionHasNoErrors(); $product = Product::query()->firstOrFail(); $first = $product->size_chart; expect($first)->not->toBeNull(); Storage::disk('local')->assertExists($first); put(route('product.update', $product), productUpdatePayload())->assertSessionHasNoErrors(); $second = $product->refresh()->size_chart; expect($second)->not->toBeNull()->not->toBe($first); Storage::disk('local')->assertExists($second); // The file it replaced goes once the save is committed. Storage::disk('local')->assertMissing($first); }); }); describe('tags', function () { it('lists the tags on the record page', function () { $product = Product::factory()->create(); $picked = Tag::factory()->create(); $product->tags()->attach($picked); actingAs(userCan(['product.view'])); get(route('product.show', $product)) ->assertInertia(fn (Assert $page) => $page ->where('item.tags.0.id', $picked->id) ->where('item.tags.0.name', $picked->name)); }); it('takes tag_ids left out of an edit as none left', function () { actingAs(userCan(['product.edit'])); $product = Product::factory()->create(); $product->tags()->attach(Tag::factory()->create()); put(route('product.update', $product), array_diff_key(productUpdatePayload(), ['tag_ids' => true])) ->assertSessionHasNoErrors(); expect($product->tags()->count())->toBe(0); }); }); describe('stamps', function () { it('stamps published_at on a record created with status active', function () { $user = userCan(['product.create']); actingAs($user); post(route('product.store'), productPayload(['status' => 'active']))->assertSessionHasNoErrors(); $created = Product::latest('id')->firstOrFail(); expect($created->getRawOriginal('published_at'))->not->toBeNull() ->and($created->published_by)->toBe($user->id); }); it('clears published_at as status leaves active, and stamps it again as it comes back', function () { $user = userCan(['product.edit']); actingAs($user); $product = Product::factory()->create(['status' => 'active', 'published_at' => now()->subDay()]); put(route('product.update', $product), productUpdatePayload(['status' => 'draft']))->assertSessionHasNoErrors(); expect($product->refresh()->getRawOriginal('published_at'))->toBeNull(); put(route('product.update', $product), productUpdatePayload(['status' => 'active']))->assertSessionHasNoErrors(); expect($product->refresh()->getRawOriginal('published_at'))->not->toBeNull() ->and($product->published_by)->toBe($user->id); }); }); describe('destroy', function () { it('soft-deletes a record', function () { actingAs(userCan(['product.delete'])); $product = Product::factory()->create(); delete(route('product.destroy', $product)) ->assertRedirect(route('product.index')) ->assertInertiaFlash('toast', ['type' => 'success', 'message' => __('crud.deleted')]); expect(Product::withTrashed()->find($product->id)->trashed())->toBeTrue(); assertDatabaseHas('activity_log', ['subject_type' => Product::class, 'subject_id' => $product->getKey(), 'event' => 'deleted']); }); }); describe('bulk delete', function () { it('takes the uploads with the rows it removes for good', function () { Storage::fake('local'); Storage::disk('local')->put('products/bulk-gone.txt', 'x'); $product = Product::factory()->create(); $product->forceFill(['size_chart' => 'products/bulk-gone.txt'])->saveQuietly(); $product->delete(); actingAs(makeSuperAdmin()); post(route('product.bulk-force-delete'), ['ids' => [$product->id]])->assertRedirect(); expect(Product::withoutGlobalScopes()->whereKey($product->id)->exists())->toBeFalse(); Storage::disk('local')->assertMissing('products/bulk-gone.txt'); }); }); describe('filters', function () { it('searches by name', function () { Product::factory()->create(['name' => 'Zephyr Unique']); Product::factory()->create(['name' => 'Ordinary One']); actingAs(userCan(['product.view'])); get(route('product.index', ['filter' => ['search' => 'zephyr']])) ->assertInertia(fn (Assert $page) => $page->has('items.data', 1)); }); it('filters by status', function () { Product::factory()->create(['status' => 'draft']); Product::factory()->count(2)->create(['status' => 'active']); actingAs(userCan(['product.view'])); get(route('product.index', ['filter' => ['status' => 'draft']])) ->assertInertia(fn (Assert $page) => $page->has('items.data', 1)); }); it('filters by attached tags', function () { $related = Tag::factory()->create(); $attached = Product::factory()->create(); $attached->tags()->attach($related->id); Product::factory()->create(); actingAs(userCan(['product.view'])); get(route('product.index', ['filter' => ['tags' => $related->id]])) ->assertInertia(fn (Assert $page) => $page->has('items.data', 1)); }); it('filters price by a minimum bound', function () { Product::factory()->create(['price' => 10.00]); Product::factory()->create(['price' => 99.50]); actingAs(userCan(['product.view'])); get(route('product.index', ['filter' => ['price_min' => 99.50]])) ->assertInertia(fn (Assert $page) => $page->has('items.data', 1)); }); }); describe('bulk', function () { it('bulk soft-deletes the given ids: :dataset', function (int $rows) { actingAs(userCan(['product.delete'])); $ids = Product::factory()->count($rows)->create()->pluck('id')->all(); expect(ProductStats::get()['total'])->toBe($rows); post(route('product.bulk-destroy'), ['ids' => $ids]) ->assertRedirect(route('product.index')) ->assertInertiaFlash('toast', ['type' => 'success', 'message' => trans_choice('crud.bulk_deleted', $rows, ['count' => $rows])]); expect(Product::count())->toBe(0) // Bulk writes fire no model events: the counts are retired by hand. ->and(ProductStats::get()['total'])->toBe(0); // One entry for the selection, naming what it changed. $entry = App\Models\Activity::where('event', 'deleted')->latest('id')->firstOrFail(); expect($entry->properties['count'])->toBe($rows) ->and($entry->properties['ids'])->toEqualCanonicalizing($ids); })->with(['one row' => [1], 'three rows' => [3]]); it('refuses a selection that is not one: :dataset', function (array $selection) { actingAs(userCan(['product.delete'])); post(route('product.bulk-destroy'), $selection)->assertSessionHasErrors(); })->with([ 'neither ids nor all' => [[]], 'ids that are not a list' => [['ids' => 'not-a-list']], 'an id that names nothing' => [['ids' => [999999]]], 'more ids than a request may carry' => [['ids' => range(1, 1001)]], 'an "all" that is not a flag' => [['all' => 'maybe']], ]); it('deletes every row the filters match, and only those', function () { actingAs(userCan(['product.delete'])); $matched = Product::factory()->create(['name' => 'Zephyr Unique']); $kept = Product::factory()->create(['name' => 'Ordinary One']); post(route('product.bulk-destroy'), ['all' => true, 'filter' => ['search' => 'zephyr']]) ->assertRedirect(route('product.index')); expect(Product::find($matched->id))->toBeNull() ->and(Product::find($kept->id))->not->toBeNull(); }); it('refuses more than a thousand rows named in one bulk request', function () { actingAs(userCan(['product.delete'])); post(route('product.bulk-destroy'), ['ids' => range(1, 1001)]) ->assertSessionHasErrors('ids'); }); it('says so when the selection deletes nothing', function () { actingAs(userCan(['product.delete'])); // Every row the filters match, of a table with none. post(route('product.bulk-destroy'), ['all' => true]) ->assertRedirect(route('product.index')) ->assertInertiaFlash('toast', ['type' => 'error', 'message' => __('crud.bulk_deleted_none')]); // Nothing changed, so nothing is filed. expect(App\Models\Activity::where('event', 'deleted')->exists())->toBeFalse(); }); it('bulk sets status on the given ids: :dataset', function (int $rows) { actingAs(userCan(['product.edit'])); $ids = Product::factory()->count($rows)->create(['status' => 'draft'])->pluck('id')->all(); expect(ProductStats::get()['active'])->toBe(0); $this->from(route('product.index')) ->post(route('product.bulk-status'), ['ids' => $ids, 'to' => 'active']) ->assertRedirect(route('product.index')) ->assertInertiaFlash('toast', ['type' => 'success', 'message' => trans_choice('crud.bulk_updated', $rows, ['count' => $rows])]); expect(Product::where('status', 'active')->count())->toBe($rows) ->and(ProductStats::get()['active'])->toBe($rows); $entry = App\Models\Activity::where('event', 'updated')->latest('id')->firstOrFail(); expect($entry->properties['count'])->toBe($rows) ->and($entry->properties['ids'])->toEqualCanonicalizing($ids) ->and($entry->properties->only(['status'])->all())->toBe(['status' => 'active']); })->with(['one row' => [1], 'two rows' => [2]]); it('refuses a bulk status target that is not one: :dataset', function (?string $to) { actingAs(userCan(['product.edit'])); $ids = Product::factory()->count(1)->create(['status' => 'draft'])->pluck('id')->all(); $this->from(route('product.index')) ->post(route('product.bulk-status'), ['ids' => $ids, ...($to === null ? [] : ['to' => $to])]) ->assertSessionHasErrors('to'); })->with(['no target' => [null], 'a target outside its cases' => ['not-a-case']]); it('says so when the bulk status selection holds nothing', function () { actingAs(userCan(['product.edit'])); $this->from(route('product.index')) ->post(route('product.bulk-status'), ['all' => true, 'to' => 'active']) ->assertRedirect(route('product.index')) ->assertInertiaFlash('toast', ['type' => 'error', 'message' => __('crud.bulk_updated_none')]); expect(App\Models\Activity::where('event', 'updated')->exists())->toBeFalse(); }); describe('concurrent edits', function () { it('refuses a save made from a stale copy', function () { $product = Product::factory()->create(['name' => 'Original']); actingAs(userCan(['product.view', 'product.edit'])); // What the first editor was handed when the form opened. $stale = RecordVersion::of($product, ['tags']); // Somebody else saves in the meantime. $product->update(['name' => 'Written By Someone Else']); put(route('product.update', $product), productUpdatePayload([ 'name' => 'Written From A Stale Form', '_version' => $stale, ]))->assertRedirect(); assertDatabaseHas('products', [ 'id' => $product->id, 'name' => 'Written By Someone Else', ]); }); it('accepts the same save once the editor reloads', function () { $product = Product::factory()->create(['name' => 'Original']); actingAs(userCan(['product.view', 'product.edit'])); put(route('product.update', $product), productUpdatePayload([ 'name' => 'Written After Reloading', '_version' => RecordVersion::of($product->fresh(), ['tags']), ]))->assertRedirect(); assertDatabaseHas('products', [ 'id' => $product->id, 'name' => 'Written After Reloading', ]); }); it('saves over a write the form did not make, such as a touch', function () { $product = Product::factory()->create(['name' => 'Original']); actingAs(userCan(['product.view', 'product.edit'])); // The version the edit form was handed. $read = get(route('product.form-data', $product))->assertOk()->json('_version'); // The application moves a column no form writes in the meantime. Product::query()->whereKey($product->getKey())->update(['updated_at' => now()->addMinute()]); put(route('product.update', $product), productUpdatePayload([ 'name' => 'Written Over A Touch', '_version' => $read, ]))->assertRedirect(); assertDatabaseHas('products', [ 'id' => $product->id, 'name' => 'Written Over A Touch', ]); }); it('leaves a client that sends no version alone', function () { $product = Product::factory()->create(['name' => 'Original']); actingAs(userCan(['product.view', 'product.edit'])); put(route('product.update', $product), productUpdatePayload(['name' => 'Written Without A Token'])) ->assertRedirect(); assertDatabaseHas('products', [ 'id' => $product->id, 'name' => 'Written Without A Token', ]); }); }); }); describe('import', function () { it('imports rows from a CSV', function () { actingAs(userCan(['product.import'])); $columns = ['category' => 'Category', 'name' => 'Name', 'slug' => 'Slug', 'sku' => 'SKU', 'status' => 'Status', 'price' => 'Price', 'compare_at_price' => 'Compare-at price', 'cost_price' => 'Cost Price', 'video_url' => 'Video', 'description' => 'Description', 'is_featured' => 'Is Featured', 'specs' => 'Specifications']; $payload = productPayload(); $payload['category'] = Category::find($payload['category_id'])?->name; // Headers are the labels the importer matches on; fputcsv so JSON, // commas and quotes survive the round trip. $buffer = fopen('php://temp', 'r+'); fputcsv($buffer, array_values($columns)); fputcsv($buffer, array_map( // A list column travels as `a; b`, as the export writes it. fn (string $column) => match (true) { is_bool($payload[$column] ?? null) => $payload[$column] ? '1' : '0', in_array($column, ['specs'], true) => (string) json_encode($payload[$column]), is_array($payload[$column] ?? null) => implode('; ', $payload[$column]), default => (string) ($payload[$column] ?? ''), }, array_keys($columns), )); rewind($buffer); $csv = (string) stream_get_contents($buffer); fclose($buffer); $file = UploadedFile::fake()->createWithContent('import.csv', $csv); $before = Product::count(); $existing = Product::query()->pluck((new Product)->getKeyName())->all(); expect(ProductStats::get()['total'])->toBe($before); post(route('product.import'), ['file' => $file]) ->assertRedirect() ->assertInertiaFlash('toast', ['type' => 'success', 'message' => trans_choice('crud.imported', 1, ['count' => 1])]); expect(Product::count())->toBe($before + 1) ->and(ProductStats::get()['total'])->toBe($before + 1); $stored = Product::query()->whereKeyNot($existing)->firstOrFail(); foreach (['name', 'sku', 'status', 'video_url', 'is_featured'] as $column) { expect($stored->getRawOriginal($column))->toEqual($payload[$column]); } }); it('says so when the sheet holds no row', function () { actingAs(userCan(['product.import'])); $file = UploadedFile::fake()->createWithContent('import.csv', implode(',', ['category' => 'Category', 'name' => 'Name', 'slug' => 'Slug', 'sku' => 'SKU', 'status' => 'Status', 'price' => 'Price', 'compare_at_price' => 'Compare-at price', 'cost_price' => 'Cost Price', 'video_url' => 'Video', 'description' => 'Description', 'is_featured' => 'Is Featured', 'specs' => 'Specifications'])."\n"); post(route('product.import'), ['file' => $file]) ->assertRedirect() ->assertInertiaFlash('toast', ['type' => 'error', 'message' => __('crud.import_empty')]); expect(Product::count())->toBe(0); }); it('refuses an import that is not a sheet: :dataset', function (mixed $file) { actingAs(userCan(['product.import'])); post(route('product.import'), $file === null ? [] : ['file' => $file]) ->assertSessionHasErrors('file'); })->with([ 'no file' => [null], 'text where the file goes' => ['not-a-file'], 'an image' => [fn () => UploadedFile::fake()->image('photo.png')], 'a sheet past 10 MB' => [fn () => UploadedFile::fake()->createWithContent('big.csv', str_repeat("a,b\n", 2_700_000))], ]); it('previews an import without writing rows', function () { actingAs(userCan(['product.import'])); $columns = ['category' => 'Category', 'name' => 'Name', 'slug' => 'Slug', 'sku' => 'SKU', 'status' => 'Status', 'price' => 'Price', 'compare_at_price' => 'Compare-at price', 'cost_price' => 'Cost Price', 'video_url' => 'Video', 'description' => 'Description', 'is_featured' => 'Is Featured', 'specs' => 'Specifications']; $payload = productPayload(); $payload['category'] = Category::find($payload['category_id'])?->name; $buffer = fopen('php://temp', 'r+'); fputcsv($buffer, array_values($columns)); fputcsv($buffer, array_map( // A list column travels as `a; b`, as the export writes it. fn (string $column) => match (true) { is_bool($payload[$column] ?? null) => $payload[$column] ? '1' : '0', in_array($column, ['specs'], true) => (string) json_encode($payload[$column]), is_array($payload[$column] ?? null) => implode('; ', $payload[$column]), default => (string) ($payload[$column] ?? ''), }, array_keys($columns), )); rewind($buffer); $csv = (string) stream_get_contents($buffer); fclose($buffer); $file = UploadedFile::fake()->createWithContent('import.csv', $csv); $before = Product::count(); post(route('product.import-preview'), ['file' => $file]) ->assertOk() ->assertJson(['valid' => 1, 'invalid' => 0, 'total' => 1]); // Dry-run writes nothing. expect(Product::count())->toBe($before); }); it('refuses a row the create form refuses', function () { actingAs(userCan(['product.import'])); $columns = ['category' => 'Category', 'name' => 'Name', 'slug' => 'Slug', 'sku' => 'SKU', 'status' => 'Status', 'price' => 'Price', 'compare_at_price' => 'Compare-at price', 'cost_price' => 'Cost Price', 'video_url' => 'Video', 'description' => 'Description', 'is_featured' => 'Is Featured', 'specs' => 'Specifications']; $payload = productPayload(['sku' => str_repeat('x', 33)]); $payload['category'] = Category::find($payload['category_id'])?->name; $buffer = fopen('php://temp', 'r+'); fputcsv($buffer, array_values($columns)); fputcsv($buffer, array_map( fn (string $column) => match (true) { is_bool($payload[$column] ?? null) => $payload[$column] ? '1' : '0', in_array($column, ['specs'], true) => (string) json_encode($payload[$column]), is_array($payload[$column] ?? null) => implode('; ', $payload[$column]), default => (string) ($payload[$column] ?? ''), }, array_keys($columns), )); rewind($buffer); $file = UploadedFile::fake()->createWithContent('import.csv', (string) stream_get_contents($buffer)); fclose($buffer); post(route('product.import-preview'), ['file' => $file]) ->assertOk() ->assertJson(['valid' => 0, 'invalid' => 1, 'total' => 1]); }); it('refuses a row whose :dataset the create form refuses', function (string $field, mixed $value) { actingAs(userCan(['product.import'])); $columns = ['category' => 'Category', 'name' => 'Name', 'slug' => 'Slug', 'sku' => 'SKU', 'status' => 'Status', 'price' => 'Price', 'compare_at_price' => 'Compare-at price', 'cost_price' => 'Cost Price', 'video_url' => 'Video', 'description' => 'Description', 'is_featured' => 'Is Featured', 'specs' => 'Specifications']; $payload = productPayload([$field => $value]); $payload['category'] = Category::find($payload['category_id'])?->name; $buffer = fopen('php://temp', 'r+'); fputcsv($buffer, array_values($columns)); fputcsv($buffer, array_map( fn (string $column) => match (true) { is_bool($payload[$column] ?? null) => $payload[$column] ? '1' : '0', in_array($column, ['specs'], true) => (string) json_encode($payload[$column]), is_array($payload[$column] ?? null) => implode('; ', $payload[$column]), default => (string) ($payload[$column] ?? ''), }, array_keys($columns), )); rewind($buffer); $file = UploadedFile::fake()->createWithContent('import.csv', (string) stream_get_contents($buffer)); fclose($buffer); post(route('product.import-preview'), ['file' => $file]) ->assertOk() ->assertJson(['valid' => 0, 'invalid' => 1, 'total' => 1]); })->with([ 'name' => ['name', str_repeat('x', 121)], 'slug' => ['slug', str_repeat('x', 141)], 'sku' => ['sku', str_repeat('x', 33)], 'status' => ['status', 'not-a-case'], 'price' => ['price', 'not-a-number'], 'compare_at_price' => ['compare_at_price', 'not-a-number'], 'cost_price' => ['cost_price', 'not-a-number'], 'video_url' => ['video_url', str_repeat('x', 501)], 'description' => ['description', str_repeat('x', 2001)], ]); // Writing one record and writing thousands are separate trusts. it('forbids import for a user who may only create', function () { actingAs(userCan(['product.create'])); $file = UploadedFile::fake()->createWithContent('import.csv', "column\n"); post(route('product.import'), ['file' => $file])->assertForbidden(); }); it('downloads a CSV import template', function () { actingAs(userCan(['product.import'])); $response = get(route('product.import-template')); $response->assertOk(); expect($response->headers->get('content-type'))->toContain('text/csv'); }); }); describe('timeline', function () { it('shows the audit timeline to super-admin only', function () { actingAs(userCan(['product.create'])); post(route('product.store'), productPayload()); $product = Product::firstOrFail(); actingAs(makeSuperAdmin()); get(route('product.show', $product)) ->assertInertia(fn (Assert $page) => $page ->has('timeline', 1) ->where('timeline.0.event', 'created')); // The per-record rail is gated on the role, not on activity-log.view. actingAs(userCan(['product.view', 'activity-log.view'])); get(route('product.show', $product)) ->assertInertia(fn (Assert $page) => $page->where('timeline', null)); }); it('records a per-field diff when a record is updated', function () { $product = Product::factory()->create(['name' => 'Before Value']); actingAs(makeSuperAdmin()); put(route('product.update', $product), productUpdatePayload(['name' => 'After Value'])); get(route('product.show', $product)) ->assertInertia(fn (Assert $page) => $page ->where('timeline.0.event', 'updated') ->has('timeline.0.changes')); }); it('files no entry for a save that changes nothing', function () { $product = Product::factory()->create(); app(UpdateProduct::class)->handle($product, ['name' => $product->name]); assertDatabaseMissing('activity_log', ['subject_type' => Product::class, 'subject_id' => $product->id, 'event' => 'updated']); }); it('records the tags a save attached and detached', function () { $product = Product::factory()->create(); [$kept, $dropped, $added] = Tag::factory()->count(3)->create()->all(); $product->tags()->sync([$kept->id, $dropped->id]); actingAs(makeSuperAdmin()); put(route('product.update', $product), productUpdatePayload(['tag_ids' => [$kept->id, $added->id]])) ->assertRedirect(); $entry = Activity::query()->where('subject_type', Product::class)->where('subject_id', $product->id)->where('event', 'updated')->firstOrFail(); expect($entry->attribute_changes['attributes']['tags'])->toBe(['attached' => [$added->id], 'detached' => [$dropped->id]]); }); // Either half alone is a change, and the same list again is none. it('records tags only added, only taken away, and not at all when they stay', function () { $product = Product::factory()->create(); [$first, $second] = Tag::factory()->count(2)->create()->all(); $product->tags()->sync([$first->id]); actingAs(makeSuperAdmin()); $entries = fn () => Activity::query()->where('subject_type', Product::class)->where('subject_id', $product->id)->where('event', 'updated')->latest('id'); put(route('product.update', $product), productUpdatePayload(['tag_ids' => [$first->id, $second->id]]))->assertRedirect(); expect($entries()->firstOrFail()->attribute_changes['attributes']['tags'])->toBe(['attached' => [$second->id], 'detached' => []]); put(route('product.update', $product->refresh()), productUpdatePayload(['tag_ids' => [$second->id]]))->assertRedirect(); expect($entries()->firstOrFail()->attribute_changes['attributes']['tags'])->toBe(['attached' => [], 'detached' => [$first->id]]); $before = $entries()->count(); put(route('product.update', $product->refresh()), productUpdatePayload(['tag_ids' => [$second->id]]))->assertRedirect(); expect($entries()->count() === $before || ! array_key_exists('tags', (array) ($entries()->firstOrFail()->attribute_changes['attributes'] ?? [])))->toBeTrue(); }); }); describe('security', function () { it('ignores a non-whitelisted sort column (A03 injection)', function () { Product::factory()->count(2)->create(); actingAs(userCan(['product.view'])); get(route('product.index', ['sort' => '-id); drop table products; --'])) ->assertInertia(fn (Assert $page) => $page->has('items.data', 2)); }); it('drops a non-fillable id from the store payload (A04 mass assignment)', function () { actingAs(userCan(['product.create'])); post(route('product.store'), productPayload(['id' => 999999])) ->assertRedirect(); expect(Product::count())->toBe(1); assertDatabaseMissing('products', ['id' => 999999]); }); }); describe('trash', function () { it('lists only trashed rows in the deleted view', function () { Product::factory()->create(); $trashed = Product::factory()->create(); $trashed->delete(); actingAs(makeSuperAdmin()); get(route('product.index', ['filter' => ['trashed' => 'only']])) ->assertInertia(fn (Assert $page) => $page ->has('items.data', 1) ->where('items.data.0.id', $trashed->id)); }); // The exports read the list's filters, so they meet the list's // rule: deleted rows only for a caller who may see the trash. it('refuses the trash to an export by a holder of product.export', function () { Product::factory()->create()->delete(); actingAs(userCan(['product.view', 'product.export'])); get(route('product.export', ['filter' => ['trashed' => 'only']]))->assertForbidden(); get(route('product.export-excel', ['filter' => ['trashed' => 'only']]))->assertForbidden(); get(route('product.export'))->assertOk(); }); it('restores a trashed row as super-admin', function () { $product = Product::factory()->create(); $product->delete(); actingAs(makeSuperAdmin()); patch(route('product.restore', $product->id)) ->assertRedirect(route('product.index', ['filter' => ['trashed' => 'only']])) ->assertInertiaFlash('toast', ['type' => 'success', 'message' => __('crud.restored')]); expect(Product::whereKey($product->id)->exists())->toBeTrue(); assertDatabaseHas('activity_log', ['subject_type' => Product::class, 'subject_id' => $product->getKey(), 'event' => 'restored']); }); it('refuses a live bulk delete of a selection made in the trash', function () { Product::factory()->create()->delete(); actingAs(makeSuperAdmin()); post(route('product.bulk-destroy'), ['all' => true, 'filter' => ['trashed' => 'only']]) ->assertStatus(422); expect(Product::onlyTrashed()->count())->toBe(1); }); // Restore and delete-for-good answer for the trash only: a live // row is not theirs to touch. it('answers 404 to restoring or deleting for good a row still live', function () { $product = Product::factory()->create(); actingAs(makeSuperAdmin()); patch(route('product.restore', $product->id))->assertNotFound(); delete(route('product.force-delete', $product->id))->assertNotFound(); expect(Product::whereKey($product->id)->exists())->toBeTrue(); }); // The permission is the rule: a role the matrix grants it to may // restore, and one without it may not. it('lets a holder of product.restore restore, and no one else', function () { $product = Product::factory()->create(); $product->delete(); actingAs(userCan(['product.view'])); patch(route('product.restore', $product->id))->assertForbidden(); expect(Product::withTrashed()->whereKey($product->id)->whereNotNull('deleted_at')->exists())->toBeTrue(); actingAs(userCan(['product.view', 'product.restore'])); patch(route('product.restore', $product->id))->assertRedirect(); expect(Product::whereKey($product->id)->exists())->toBeTrue(); }); it('permanently deletes as super-admin', function () { $product = Product::factory()->create(); $product->delete(); actingAs(makeSuperAdmin()); delete(route('product.force-delete', $product->id)) ->assertRedirect(route('product.index', ['filter' => ['trashed' => 'only']])) ->assertInertiaFlash('toast', ['type' => 'success', 'message' => __('crud.force_deleted')]); expect(Product::withTrashed()->whereKey($product->id)->exists())->toBeFalse(); assertDatabaseHas('activity_log', ['subject_type' => Product::class, 'subject_id' => $product->getKey(), 'event' => 'force-deleted']); }); it('lets a holder of product.force-delete delete for good, and no one else', function () { $product = Product::factory()->create(); $product->delete(); actingAs(userCan(['product.view', 'product.restore'])); delete(route('product.force-delete', $product->id))->assertForbidden(); expect(Product::withTrashed()->whereKey($product->id)->exists())->toBeTrue(); actingAs(userCan(['product.view', 'product.force-delete'])); delete(route('product.force-delete', $product->id))->assertRedirect(); expect(Product::withTrashed()->whereKey($product->id)->exists())->toBeFalse(); }); it('shows the deleted view to the trash permissions alone', function () { actingAs(userCan(['product.view'])); get(route('product.index', ['filter' => ['trashed' => 'only']]))->assertForbidden(); actingAs(userCan(['product.view', 'product.restore'])); get(route('product.index', ['filter' => ['trashed' => 'only']]))->assertOk(); }); it('brings a selection of the trash back at once: :dataset', function (int $rows) { $ids = Product::factory()->count($rows)->create()->each->delete()->pluck('id')->all(); actingAs(userCan(['product.restore'])); expect(ProductStats::get()['total'])->toBe(0); post(route('product.bulk-restore'), ['ids' => $ids]) ->assertRedirect(route('product.index', ['filter' => ['trashed' => 'only']])) ->assertInertiaFlash('toast', ['type' => 'success', 'message' => trans_choice('crud.bulk_restored', $rows, ['count' => $rows])]); expect(Product::whereKey($ids)->count())->toBe($rows) ->and(ProductStats::get()['total'])->toBe($rows); $entry = App\Models\Activity::where('event', 'restored')->latest('id')->firstOrFail(); expect($entry->properties['count'])->toBe($rows) ->and($entry->properties['ids'])->toEqualCanonicalizing($ids); })->with(['one row' => [1], 'two rows' => [2]]); it('deletes a selection of the trash for good at once: :dataset', function (int $rows) { $ids = Product::factory()->count($rows)->create()->each->delete()->pluck('id')->all(); actingAs(userCan(['product.force-delete'])); post(route('product.bulk-force-delete'), ['ids' => $ids]) ->assertRedirect(route('product.index', ['filter' => ['trashed' => 'only']])) ->assertInertiaFlash('toast', ['type' => 'success', 'message' => trans_choice('crud.bulk_force_deleted', $rows, ['count' => $rows])]); expect(Product::withTrashed()->whereKey($ids)->count())->toBe(0); $entry = App\Models\Activity::where('event', 'force-deleted')->latest('id')->firstOrFail(); expect($entry->properties['count'])->toBe($rows) ->and($entry->properties['ids'])->toEqualCanonicalizing($ids); })->with(['one row' => [1], 'two rows' => [2]]); it('brings back every trashed row the filters match, and no live one', function () { $trashed = Product::factory()->count(2)->create()->each->delete()->pluck('id')->all(); Product::factory()->create(); actingAs(userCan(['product.restore'])); post(route('product.bulk-restore'), ['all' => true, 'filter' => ['trashed' => 'only']]) ->assertInertiaFlash('toast', ['type' => 'success', 'message' => trans_choice('crud.bulk_restored', 2)]); expect(Product::whereKey($trashed)->count())->toBe(2) ->and(Product::onlyTrashed()->count())->toBe(0); }); // "All" in the trash is the trash alone, whatever filter the // request carries: a live row is never deleted for good with it. it('deletes for good every trashed row selected as all, and no live one', function () { $trashed = Product::factory()->count(2)->create()->each->delete()->pluck('id')->all(); $live = Product::factory()->create(); actingAs(userCan(['product.force-delete'])); post(route('product.bulk-force-delete'), ['all' => true]) ->assertRedirect(); expect(Product::withTrashed()->whereKey($trashed)->count())->toBe(0) ->and(Product::find($live->id))->not->toBeNull(); }); it('brings back only the trashed rows the search matches', function () { $matched = Product::factory()->create(['name' => 'Zephyr Unique']); $other = Product::factory()->create(['name' => 'Ordinary One']); $matched->delete(); $other->delete(); actingAs(userCan(['product.restore'])); post(route('product.bulk-restore'), ['all' => true, 'filter' => ['trashed' => 'only', 'search' => 'zephyr']]) ->assertRedirect(); expect(Product::find($matched->id))->not->toBeNull() ->and(Product::onlyTrashed()->whereKey($other->id)->exists())->toBeTrue(); }); it('says so when the trash selection holds nothing', function () { actingAs(userCan(['product.restore', 'product.force-delete'])); post(route('product.bulk-restore'), ['all' => true, 'filter' => ['trashed' => 'only']]) ->assertInertiaFlash('toast', ['type' => 'error', 'message' => __('crud.bulk_restored_none')]); post(route('product.bulk-force-delete'), ['all' => true, 'filter' => ['trashed' => 'only']]) ->assertInertiaFlash('toast', ['type' => 'error', 'message' => __('crud.bulk_force_deleted_none')]); expect(App\Models\Activity::whereIn('event', ['restored', 'force-deleted'])->exists())->toBeFalse(); }); }); describe('inline productVariants', function () { it('deletes a ProductVariant through the parent, and files the audit entry', function () { $product = Product::factory()->create(); $child = ProductVariant::factory()->create(['product_id' => $product->id]); actingAs(userCan(['product.view', 'product-variant.delete'])); delete("/product/{$product->id}/product-variant/{$child->id}")->assertRedirect(); expect(ProductVariant::find($child->id))->toBeNull(); assertDatabaseHas('activity_log', ['subject_type' => $child->getMorphClass(), 'subject_id' => $child->id, 'event' => 'deleted']); }); it('refuses to delete a ProductVariant through the parent without product-variant.delete', function () { $product = Product::factory()->create(); $child = ProductVariant::factory()->create(['product_id' => $product->id]); actingAs(userCan(['product.view'])); delete("/product/{$product->id}/product-variant/{$child->id}")->assertForbidden(); expect(ProductVariant::find($child->id))->not->toBeNull(); }); }); describe('inline reviews', function () { it('deletes a Review through the parent, and files the audit entry', function () { $product = Product::factory()->create(); $child = Review::factory()->create(['product_id' => $product->id]); actingAs(userCan(['product.view', 'review.delete'])); delete("/product/{$product->id}/review/{$child->id}")->assertRedirect(); expect(Review::find($child->id))->toBeNull(); assertDatabaseHas('activity_log', ['subject_type' => $child->getMorphClass(), 'subject_id' => $child->id, 'event' => 'deleted']); }); it('refuses to delete a Review through the parent without review.delete', function () { $product = Product::factory()->create(); $child = Review::factory()->create(['product_id' => $product->id]); actingAs(userCan(['product.view'])); delete("/product/{$product->id}/review/{$child->id}")->assertForbidden(); expect(Review::find($child->id))->not->toBeNull(); }); }); describe('api', function () { it('rejects unauthenticated API requests', function () { getJson('/api/v1/products')->assertUnauthorized(); }); it('lists records for a token with product.view', function () { Product::factory()->count(3)->create(); Sanctum::actingAs(userCan(['product.view']), ['*']); getJson('/api/v1/products') ->assertOk() ->assertJsonStructure(['data', 'links', 'meta']) ->assertJsonCount(3, 'data'); }); it('forbids a token without product.view', function () { Sanctum::actingAs(userCan([]), ['*']); getJson('/api/v1/products')->assertForbidden(); }); it('honours a read-only token scope', function () { Sanctum::actingAs(userCan(['product.view', 'product.create']), ['read']); getJson('/api/v1/products')->assertOk(); post('/api/v1/products', productPayload())->assertForbidden(); }); it('creates, shows, updates and deletes through the API', function () { Sanctum::actingAs(makeSuperAdmin(), ['*']); $product = Product::factory()->create(); getJson("/api/v1/products/{$product->id}") ->assertOk() ->assertJsonPath('data.id', $product->id); // Relative to what was there: a migration may seed default rows. $before = Product::count(); $created = post('/api/v1/products', productPayload())->assertCreated(); expect(Product::count())->toBe($before + 1) // Where it lives and its version: the first conditional write needs no read. ->and($created->headers->get('Location'))->toBe(route('api.v1.products.show', $created->json('data.id'))) ->and($created->headers->get('ETag'))->toBe(getJson($created->headers->get('Location'))->headers->get('ETag')); put("/api/v1/products/{$product->id}", productUpdatePayload(['name' => 'Renamed Value'])) ->assertOk(); expect($product->refresh()->name)->toBe('Renamed Value'); delete("/api/v1/products/{$product->id}")->assertNoContent(); }); // An unknown filter, sort or include is a 400 naming it, never a silent // no-op — a dropped filter hands the caller a complete set they believe // was narrowed. it('refuses an unknown filter, sort and include with 400', function () { Sanctum::actingAs(userCan(['product.view']), ['*']); $product = Product::factory()->create(); getJson('/api/v1/products?filter[no_such_column]=x')->assertStatus(400); getJson('/api/v1/products?sort=no_such_column')->assertStatus(400); getJson('/api/v1/products?include=noSuchRelation')->assertStatus(400); // The record too, as the list does. getJson("/api/v1/products/{$product->id}?include=noSuchRelation")->assertStatus(400)->assertJson(['code' => 'invalid_query']); }); it('refuses a per_page outside the allowed set with 400', function () { Product::factory()->count(2)->create(); Sanctum::actingAs(userCan(['product.view']), ['*']); getJson('/api/v1/products?per_page=9999')->assertStatus(400)->assertJson(['code' => 'invalid_query']); getJson('/api/v1/products?per_page=25')->assertOk()->assertJsonPath('meta.per_page', 25); getJson('/api/v1/products')->assertOk()->assertJsonPath('meta.per_page', PageSize::API); }); it('refuses a suspended account\'s token', function () { $user = userCan(['product.view']); $user->forceFill(['suspended_at' => now()])->save(); Sanctum::actingAs($user, ['*']); getJson('/api/v1/products')->assertForbidden(); }); it('stores the files a create sends through the API', function () { Sanctum::actingAs(userCan(['product.create']), ['*']); $payload = productPayload(); post('/api/v1/products', $payload)->assertCreated(); $stored = Product::query()->latest('id')->firstOrFail(); expect($stored->photos)->toHaveCount(count($payload['photos_new'])) ->and($stored->size_chart)->not->toBeNull(); Storage::disk('local')->assertExists([...$stored->photos, $stored->size_chart]); }); it('embeds each relation ?include names, and none it does not', function () { Sanctum::actingAs(userCan(['product.view']), ['*']); $product = Product::factory()->create(['published_by' => User::factory()]); getJson("/api/v1/products/{$product->id}") ->assertOk() ->assertJsonMissingPath('data.category'); getJson("/api/v1/products/{$product->id}?include=category,publishedByRef,productVariants,reviews,coupons,tags") ->assertOk() ->assertJsonPath('data.category.id', $product->category_id) ->assertJsonPath('data.publishedByRef.id', $product->published_by) ->assertJsonStructure(['data' => ['productVariants', 'reviews', 'coupons', 'tags']]); getJson('/api/v1/products?include=category,publishedByRef,productVariants,reviews,coupons,tags') ->assertOk() ->assertJsonStructure(['data' => ['*' => ['category']]]); }); // The document is how a client learns the body: a key it names that the // requests do not read is a value the server silently drops. it('documents only the input its requests read', function () { $schemas = app(OpenApiGenerator::class)->generate('admin')['components']['schemas']; expect(array_values(array_diff(array_keys($schemas['ProductCreateInput']['properties']), array_keys((new StoreProductRequest)->rules()))))->toBe([]); expect(array_values(array_diff(array_keys($schemas['ProductUpdateInput']['properties']), array_keys((new UpdateProductRequest)->formRules()))))->toBe([]) // PATCH: the same fields, none of them required. ->and($schemas['ProductPatchInput'])->not->toHaveKey('required'); }); it('leaves the lists an update does not send as they are', function () { Sanctum::actingAs(makeSuperAdmin(), ['*']); Storage::fake('local'); $product = Product::factory()->create(); $product->tags()->sync(Tag::factory()->count(2)->create()->modelKeys()); $product->forceFill(['photos' => ['products/kept-a.png', 'products/kept-b.png']])->save(); put("/api/v1/products/{$product->id}", productUpdatePayload(['photos_new' => []]))->assertOk(); expect($product->tags()->count())->toBe(2); expect($product->refresh()->photos)->toBe(['products/kept-a.png', 'products/kept-b.png']); put("/api/v1/products/{$product->id}", productUpdatePayload(['photos_new' => [], 'tag_ids' => [], 'photos_existing' => []]))->assertOk(); expect($product->tags()->count())->toBe(0); expect($product->refresh()->photos)->toBe([]); }); it('changes on PATCH only the fields it sends', function () { Sanctum::actingAs(userCan(['product.edit', 'product.view']), ['*']); // As stored: a factory's in-memory values (a date with a time) are not. $product = Product::factory()->create()->refresh(); $before = $product->only(['category_id', 'slug', 'sku', 'status', 'price', 'compare_at_price', 'cost_price', 'video_url', 'description', 'is_featured', 'specs']); patchJson("/api/v1/products/{$product->id}", ['name' => 'Patched Value'])->assertOk(); expect($product->refresh()->name)->toBe('Patched Value') ->and($product->only(['category_id', 'slug', 'sku', 'status', 'price', 'compare_at_price', 'cost_price', 'video_url', 'description', 'is_featured', 'specs']))->toEqual($before); }); it('refuses a PUT that leaves out a required field', function () { Sanctum::actingAs(userCan(['product.edit', 'product.view']), ['*']); $product = Product::factory()->create(); putJson("/api/v1/products/{$product->id}", array_diff_key(productUpdatePayload(), ['category_id' => true])) ->assertUnprocessable() ->assertJsonValidationErrors('category_id'); }); it('refuses to change sku, fixed once created, and takes it back unchanged', function () { Sanctum::actingAs(userCan(['product.edit', 'product.view']), ['*']); $product = Product::factory()->create(); patchJson("/api/v1/products/{$product->id}", ['sku' => 'Changed']) ->assertUnprocessable() ->assertJsonValidationErrors('sku'); patchJson("/api/v1/products/{$product->id}", ['sku' => $product->getRawOriginal('sku')])->assertOk(); }); it('counts productVariants on a list when asked, and prints the count', function () { Sanctum::actingAs(userCan(['product.view']), ['*']); Product::factory()->create(); $row = getJson('/api/v1/products?include=productVariantsCount,productVariantsExists')->assertOk()->json('data.0'); expect($row)->toHaveKeys(['product_variants_count', 'product_variants_exists']); getJson('/api/v1/products?include=categoryCount')->assertStatus(400); }); it('answers a missing record and a refused body as problems a client can read', function () { Sanctum::actingAs(makeSuperAdmin(), ['*']); getJson('/api/v1/products/999999') ->assertNotFound() ->assertJson(['code' => 'not_found']); postJson('/api/v1/products', []) ->assertUnprocessable() ->assertJson(['code' => 'validation_failed']) ->assertJsonValidationErrors('name'); }); }); describe('api conditional writes', function () { it('hands out an ETag on read', function () { Sanctum::actingAs(makeSuperAdmin(), ['*']); $product = Product::factory()->create(); $etag = getJson("/api/v1/products/{$product->id}")->assertOk()->headers->get('ETag'); expect($etag)->not->toBeNull(); }); it('answers 304 to a client that already holds this version', function () { Sanctum::actingAs(makeSuperAdmin(), ['*']); $product = Product::factory()->create(); $etag = (string) getJson("/api/v1/products/{$product->id}")->headers->get('ETag'); getJson("/api/v1/products/{$product->id}", ['If-None-Match' => $etag])->assertStatus(304)->assertContent(''); getJson("/api/v1/products/{$product->id}", ['If-None-Match' => '"stale"'])->assertOk(); }); it('refuses a write whose If-Match no longer holds', function () { Sanctum::actingAs(makeSuperAdmin(), ['*']); $product = Product::factory()->create(['name' => 'Original']); $stale = '"'.RecordVersion::of($product, ['tags']).'"'; // Somebody else writes in between. $product->update(['name' => 'Written By Someone Else']); putJson("/api/v1/products/{$product->id}", productUpdatePayload(['name' => 'Written From Stale']), ['If-Match' => $stale]) ->assertStatus(412); expect($product->refresh()->name)->toBe('Written By Someone Else'); }); it('refuses a delete whose If-Match no longer holds', function () { Sanctum::actingAs(makeSuperAdmin(), ['*']); $product = Product::factory()->create(['name' => 'Original']); $stale = '"'.RecordVersion::of($product, ['tags']).'"'; $product->update(['name' => 'Written By Someone Else']); deleteJson("/api/v1/products/{$product->id}", [], ['If-Match' => $stale]) ->assertStatus(412); expect(Product::whereKey($product->id)->exists())->toBeTrue(); }); it('deletes a record whose If-Match still holds', function () { Sanctum::actingAs(makeSuperAdmin(), ['*']); $product = Product::factory()->create(['name' => 'Original']); $etag = getJson("/api/v1/products/{$product->id}")->assertOk()->headers->get('ETag'); deleteJson("/api/v1/products/{$product->id}", [], ['If-Match' => $etag]) ->assertNoContent(); expect(Product::whereKey($product->id)->exists())->toBeFalse(); }); it('accepts a write whose If-Match still holds', function () { Sanctum::actingAs(makeSuperAdmin(), ['*']); $product = Product::factory()->create(['name' => 'Original']); $etag = getJson("/api/v1/products/{$product->id}")->assertOk()->headers->get('ETag'); putJson("/api/v1/products/{$product->id}", productUpdatePayload(['name' => 'Written With A Live Tag']), ['If-Match' => (string) $etag]) ->assertOk(); expect($product->refresh()->name)->toBe('Written With A Live Tag'); }); it('leaves a client that sends no If-Match alone', function () { Sanctum::actingAs(makeSuperAdmin(), ['*']); $product = Product::factory()->create(['name' => 'Original']); // Opt-in, as an absent `_version` is on the web. putJson("/api/v1/products/{$product->id}", productUpdatePayload(['name' => 'Written Unconditionally'])) ->assertOk(); expect($product->refresh()->name)->toBe('Written Unconditionally'); }); it('compares If-Match strongly: a weak tag never matches', function () { Sanctum::actingAs(makeSuperAdmin(), ['*']); $product = Product::factory()->create(['name' => 'Original']); putJson("/api/v1/products/{$product->id}", productUpdatePayload(['name' => 'Written With A Weak Tag']), ['If-Match' => 'W/"'.RecordVersion::of($product, ['tags']).'"']) ->assertStatus(412); expect($product->refresh()->name)->toBe('Original'); }); it('answers 428 when writes must be conditional and this one is not', function () { config(['api.conditional_writes' => 'required']); Sanctum::actingAs(makeSuperAdmin(), ['*']); $product = Product::factory()->create(); putJson("/api/v1/products/{$product->id}", productUpdatePayload())->assertStatus(428); $etag = getJson("/api/v1/products/{$product->id}")->assertOk()->headers->get('ETag'); putJson("/api/v1/products/{$product->id}", productUpdatePayload(), ['If-Match' => (string) $etag])->assertOk(); }); it('hands back the ETag a read of the written record gives', function () { Sanctum::actingAs(makeSuperAdmin(), ['*']); $product = Product::factory()->create(); $written = putJson("/api/v1/products/{$product->id}", productUpdatePayload())->assertOk()->headers->get('ETag'); expect(getJson("/api/v1/products/{$product->id}")->headers->get('ETag'))->toBe($written); }); it('answers a stale If-Match with 412 before it reads the body', function () { Sanctum::actingAs(makeSuperAdmin(), ['*']); $product = Product::factory()->create(['name' => 'Original']); $stale = '"'.RecordVersion::of($product, ['tags']).'"'; $product->update(['name' => 'Written By Someone Else']); putJson("/api/v1/products/{$product->id}", ['name' => ''], ['If-Match' => $stale]) ->assertStatus(412); }); it('refuses, inside the write, a version that moved after it was read', function () { $product = Product::factory()->create(['name' => 'Original']); $read = RecordVersion::of($product, ['tags']); Product::query()->whereKey($product->id)->update(['name' => 'Written By Someone Else']); expect(fn () => app(UpdateProduct::class)->handle($product, productUpdatePayload(['name' => 'Written From Stale']), expected: [$read])) ->toThrow(StaleRecord::class); expect($product->refresh()->name)->toBe('Written By Someone Else'); }); }); /** * Rows until publiclyVisible() shows one and hides one, or 24 are made: the * factory picks each row's state at random, and a check that waits on chance * is skipped, or passes having checked nothing, by chance. * * @param array $attributes * @return array{0: Product|null, 1: Product|null} */ function productPublicRows(array $attributes = []): array { $shown = $hidden = null; for ($round = 0; $round < 3 && ($shown === null || $hidden === null); $round++) { $rows = Product::factory()->count(8)->create($attributes); $visible = Product::query()->publiclyVisible()->whereKey($rows->modelKeys())->pluck('id')->all(); $shown ??= $rows->first(fn (Product $row): bool => in_array($row->id, $visible, true)); $hidden ??= $rows->first(fn (Product $row): bool => ! in_array($row->id, $visible, true)); } return [$shown, $hidden]; } describe('public api', function () { it('lists products to a guest, without a token', function () { Product::factory()->count(3)->create(); getJson(route('api.public.products.index')) ->assertOk() ->assertJsonStructure(['data', 'links', 'meta']) ->assertJsonMissingPath('data.0.cost_price') ->assertJsonMissingPath('data.0.published_by') ->assertJsonMissingPath('data.0.created_at') ->assertJsonMissingPath('data.0.updated_at'); }); it('lists exactly what publiclyVisible() lets through', function () { Product::factory()->count(6)->create(); $visible = Product::query()->publiclyVisible()->pluck('slug')->map(fn (mixed $v): string => (string) $v)->sort()->values()->all(); $listed = collect(getJson(route('api.public.products.index'))->assertOk()->json('data')) ->pluck('id')->map(fn (mixed $v): string => (string) $v)->sort()->values()->all(); expect($listed)->toBe($visible); }); it('shows a product anyone may see, and answers 404 for one the scope hides', function () { [$shown, $hidden] = productPublicRows(); if ($shown === null) { test()->markTestSkipped('Product::scopePubliclyVisible() hides every row the factory made.'); } $read = getJson(route('api.public.products.show', ['product' => $shown->slug])) ->assertOk() ->assertJsonPath('data.id', $shown->slug); // The same for anyone: cacheable, then revalidated by its ETag. expect($read->headers->get('Cache-Control'))->toContain('public')->toContain('max-age='); getJson(route('api.public.products.show', ['product' => $shown->slug]), ['If-None-Match' => (string) $read->headers->get('ETag')]) ->assertStatus(304); if ($hidden === null) { test()->markTestSkipped('Product::scopePubliclyVisible() hid none of the rows the factory made — narrow the scope to what anyone may see, or let the factory make a row it hides, and this is checked.'); } getJson(route('api.public.products.show', ['product' => $hidden->slug]))->assertNotFound(); }); it('writes nothing', function () { foreach (['store', 'update', 'destroy'] as $verb) { expect(Route::has("api.public.products.{$verb}"))->toBeFalse(); } post(route('api.public.products.index'), [])->assertStatus(405); }); it('speaks in public ids, never the integers behind them', function () { productPublicRows(); $listed = getJson(route('api.public.products.index'))->assertOk()->json('data'); if ($listed === []) { test()->markTestSkipped('Product::scopePubliclyVisible() hides every row the factory made.'); } foreach ($listed as $item) { expect($item['id'])->toBeString() ->and($item['category_id'] ?? null)->not->toBeInt(); } }); it('serves the files of a product anyone may see, in place and cacheable — and of no other', function () { Storage::disk('local')->put('public-api/pixel.png', (string) base64_decode('iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mNkYAAAAAYAAjCB0C8AAAAASUVORK5CYII=')); [$shown, $hidden] = productPublicRows(['photos' => ['public-api/pixel.png']]); if ($shown === null) { test()->markTestSkipped('Product::scopePubliclyVisible() hides every row the factory made.'); } $response = get(route('api.public.products.file', ['product' => $shown->slug, 'column' => 'photos', 'path' => 'public-api/pixel.png']))->assertOk(); expect((string) $response->headers->get('Cache-Control'))->toContain('public') ->and((string) $response->headers->get('Content-Disposition'))->toStartWith('inline'); get(route('api.public.products.file', ['product' => $shown->slug, 'column' => 'photos', 'path' => 'public-api/pixel.png', 'size' => 'thumb']))->assertOk(); get(route('api.public.products.file', ['product' => $shown->slug, 'column' => 'photos', 'path' => 'public-api/pixel.png', 'size' => 'nosuchsize']))->assertStatus(400); if ($hidden === null) { test()->markTestSkipped('Product::scopePubliclyVisible() hid none of the rows the factory made — narrow the scope to what anyone may see, or let the factory make a row it hides, and this is checked.'); } get(route('api.public.products.file', ['product' => $hidden->slug, 'column' => 'photos', 'path' => 'public-api/pixel.png']))->assertNotFound(); }); }); arch('the product controllers leave the audit trail to the actions') ->expect('activity') ->not->toBeUsedIn('App\Http\Controllers\Product'); arch('each product action is one final class with one handle()') ->expect('App\Actions\Product') ->toBeFinal() ->toHaveMethod('handle');