Compare commits

..

2 Commits

6 changed files with 256 additions and 92 deletions

View File

@@ -41,7 +41,11 @@ class ProductVariantController extends Controller
$producto = $this->resolveScopedProduct($tenant, $producto); $producto = $this->resolveScopedProduct($tenant, $producto);
$productVariant = $this->resolveScopedVariant($producto, $productVariant); $productVariant = $this->resolveScopedVariant($producto, $productVariant);
return ProductVariantResource::make($productVariant->load(['product', 'definitions.productAttribute.attribute.options', 'attachments'])); return ProductVariantResource::make($productVariant->load([
'attachments' => fn ($query) => $query->orderBy('attachments.id'),
'definitions.productAttribute.attribute.options',
'product.attachments' => fn ($query) => $query->orderBy('attachments.id'),
]));
} }
public function update(UpdateProductVariantRequest $request, Tenant $tenant, Product $producto, ProductVariant $productVariant, ProductService $productService): ProductVariantResource public function update(UpdateProductVariantRequest $request, Tenant $tenant, Product $producto, ProductVariant $productVariant, ProductService $productService): ProductVariantResource

View File

@@ -2,11 +2,12 @@
namespace App\Domains\Catalog\Resources; namespace App\Domains\Catalog\Resources;
use App\Domains\Catalog\Models\Product;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource; use Illuminate\Http\Resources\Json\JsonResource;
/** /**
* @mixin \App\Domains\Catalog\Models\Product * @mixin Product
*/ */
class ProductResource extends JsonResource class ProductResource extends JsonResource
{ {
@@ -25,13 +26,24 @@ class ProductResource extends JsonResource
'precio' => $this->precio, 'precio' => $this->precio,
'category' => $this->whenLoaded('category', fn () => $this->category?->nombre), 'category' => $this->whenLoaded('category', fn () => $this->category?->nombre),
'brand' => $this->whenLoaded('brand', fn () => $this->brand?->nombre), 'brand' => $this->whenLoaded('brand', fn () => $this->brand?->nombre),
'images' => $this->whenLoaded('attachments', fn () => 'images' => $this->whenLoaded('attachments', fn () => $this->attachments
$this->attachments
->map(fn ($attachment) => $attachment->getTemporaryUrl(1440)) ->map(fn ($attachment) => $attachment->getTemporaryUrl(1440))
->values() ->values()
), ),
'attributes' => AttributeResource::collection($this->whenLoaded('attributes')), 'attributes' => AttributeResource::collection($this->whenLoaded('attributes')),
'variants' => ProductVariantResource::collection($this->whenLoaded('variants')), 'variants_map' => $this->whenLoaded('variants', fn () => $this->variants
->map(fn ($variant) => [
'variant_id' => $variant->id,
'stock' => $variant->stock,
'attributes' => $variant->definitions
->mapWithKeys(fn ($definition) => [
$definition->productAttribute?->attribute?->codigo => $definition->value,
])
->filter(fn ($value, $key) => $key !== null)
->toArray(),
])
->values()
),
'variant' => $this->when( 'variant' => $this->when(
$this->getSelectedVariant() !== null, $this->getSelectedVariant() !== null,
fn () => ProductVariantResource::make($this->getSelectedVariant()) fn () => ProductVariantResource::make($this->getSelectedVariant())

View File

@@ -2,11 +2,12 @@
namespace App\Domains\Catalog\Resources; namespace App\Domains\Catalog\Resources;
use App\Domains\Catalog\Models\ProductVariant;
use Illuminate\Http\Request; use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource; use Illuminate\Http\Resources\Json\JsonResource;
/** /**
* @mixin \App\Domains\Catalog\Models\ProductVariant * @mixin ProductVariant
*/ */
class ProductVariantResource extends JsonResource class ProductVariantResource extends JsonResource
{ {
@@ -35,13 +36,19 @@ class ProductVariantResource extends JsonResource
->values(); ->values();
} }
// Fallback: use product-level attachments when the variant has none if ($this->relationLoaded('fallbackAttachments')) {
$this->loadMissing('product.attachments'); return $this->fallbackAttachments
->map(fn ($attachment) => $attachment->getTemporaryUrl(1440))
->values();
}
return $this->product?->attachments if ($this->relationLoaded('product') && $this->product?->relationLoaded('attachments')) {
?->map(fn ($attachment) => $attachment->getTemporaryUrl(1440)) return $this->product->attachments
?->values() ->map(fn ($attachment) => $attachment->getTemporaryUrl(1440))
?? collect(); ->values();
}
return collect();
}), }),
]; ];
} }

View File

@@ -7,12 +7,15 @@ use App\Domains\Catalog\Models\Attribute;
use App\Domains\Catalog\Models\Product; use App\Domains\Catalog\Models\Product;
use App\Domains\Catalog\Models\ProductVariant; use App\Domains\Catalog\Models\ProductVariant;
use App\Domains\Tenant\Models\Tenant; use App\Domains\Tenant\Models\Tenant;
use Illuminate\Contracts\Pagination\LengthAwarePaginator;
use Illuminate\Http\UploadedFile; use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\DB; use Illuminate\Support\Facades\DB;
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
class ProductService class ProductService
{ {
public function __construct(protected AttachmentService $attachmentService) {} public function __construct(protected AttachmentService $attachmentService) {}
/** /**
* Create a product. * Create a product.
* *
@@ -248,7 +251,7 @@ class ProductService
/** /**
* Get products for a tenant with resolved first image (with fallback to first variant's first image). * Get products for a tenant with resolved first image (with fallback to first variant's first image).
*/ */
public function getProductos(Tenant $tenant): \Illuminate\Contracts\Pagination\LengthAwarePaginator public function getProductos(Tenant $tenant): LengthAwarePaginator
{ {
$products = Product::query() $products = Product::query()
->where('tenant_codigo', $tenant->codigo) ->where('tenant_codigo', $tenant->codigo)
@@ -282,33 +285,29 @@ class ProductService
public function getProductDetail(Tenant $tenant, Product $product, ?int $variantId = null): Product public function getProductDetail(Tenant $tenant, Product $product, ?int $variantId = null): Product
{ {
$product->load([ $product->load([
'attachments', 'attachments' => fn ($query) => $query->orderBy('attachments.id'),
'attributes.options',
'brand', 'brand',
'category', 'category',
'attributes.options', 'variants' => fn ($query) => $query->orderBy('id'),
'variants.definitions.productAttribute.attribute.options', 'variants.definitions.productAttribute.attribute.options',
]); ]);
$selectedVariantQuery = $product->variants()
->with([
'attachments',
'definitions.productAttribute.attribute.options',
]);
$selectedVariant = $variantId !== null $selectedVariant = $variantId !== null
? $selectedVariantQuery->whereKey($variantId)->first() ? $product->variants->firstWhere('id', $variantId)
: null; : $product->variants->first(fn (ProductVariant $variant) => $variant->stock > 0);
if ($selectedVariant === null) { if ($variantId !== null && $selectedVariant === null) {
$selectedVariant = $product->variants() throw new NotFoundHttpException('Product variant not found for product.');
->with([
'attachments',
'definitions.productAttribute.attribute.options',
])
->first();
} }
if ($selectedVariant) { $selectedVariant ??= $product->variants->first();
if ($selectedVariant !== null) {
$selectedVariant->load([
'attachments' => fn ($query) => $query->orderBy('attachments.id'),
]);
$selectedVariant->setRelation('fallbackAttachments', $product->attachments);
$product->setSelectedVariant($selectedVariant); $product->setSelectedVariant($selectedVariant);
} }

View File

@@ -38,6 +38,10 @@ return new class extends Migration
}); });
// 4. Point variant values to the product-attribute pivot instead of the base attribute // 4. Point variant values to the product-attribute pivot instead of the base attribute
Schema::table('productos_variantes_values', function (Blueprint $table) {
$table->index('producto_variante_id', 'prod_var_values_variant_id_index');
});
Schema::table('productos_variantes_values', function (Blueprint $table) { Schema::table('productos_variantes_values', function (Blueprint $table) {
$table->dropForeign('productos_variantes_definiciones_attribute_id_foreign'); $table->dropForeign('productos_variantes_definiciones_attribute_id_foreign');
$table->dropUnique('prod_var_def_variant_attr_unique'); $table->dropUnique('prod_var_def_variant_attr_unique');
@@ -85,6 +89,10 @@ return new class extends Migration
$table->unique(['producto_variante_id', 'attribute_id'], 'prod_var_def_variant_attr_unique'); $table->unique(['producto_variante_id', 'attribute_id'], 'prod_var_def_variant_attr_unique');
}); });
Schema::table('productos_variantes_values', function (Blueprint $table) {
$table->dropIndex('prod_var_values_variant_id_index');
});
Schema::dropIfExists('products_attributes'); Schema::dropIfExists('products_attributes');
Schema::rename('productos_variantes_values', 'productos_variantes_definiciones'); Schema::rename('productos_variantes_values', 'productos_variantes_definiciones');
Schema::rename('attribute', 'productos_attributes'); Schema::rename('attribute', 'productos_attributes');

View File

@@ -2,8 +2,11 @@
namespace Tests\Feature\Catalog; namespace Tests\Feature\Catalog;
use App\Domains\Attachable\Enums\AttachmentType;
use App\Domains\Attachable\Models\Attachment;
use App\Domains\Catalog\Models\Attribute; use App\Domains\Catalog\Models\Attribute;
use App\Domains\Catalog\Models\Product; use App\Domains\Catalog\Models\Product;
use App\Domains\Catalog\Models\ProductAttribute;
use App\Domains\Catalog\Models\ProductVariant; use App\Domains\Catalog\Models\ProductVariant;
use App\Domains\Tenant\Models\Tenant; use App\Domains\Tenant\Models\Tenant;
use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Foundation\Testing\RefreshDatabase;
@@ -15,8 +18,11 @@ class ProductControllerTest extends TestCase
use RefreshDatabase; use RefreshDatabase;
private Tenant $tenant; private Tenant $tenant;
private Attribute $sizeAttr; private Attribute $sizeAttr;
private Attribute $colorAttr; private Attribute $colorAttr;
private Attribute $extraAttr; private Attribute $extraAttr;
protected function setUp(): void protected function setUp(): void
@@ -358,7 +364,7 @@ class ProductControllerTest extends TestCase
'options' => [ 'options' => [
['value' => 'P', 'label' => 'Piqueno'], ['value' => 'P', 'label' => 'Piqueno'],
['value' => 'M', 'label' => 'Medio'], ['value' => 'M', 'label' => 'Medio'],
] ],
]); ]);
// 2. Create product and associate attribute // 2. Create product and associate attribute
@@ -384,14 +390,13 @@ class ProductControllerTest extends TestCase
[ [
'attribute_id' => $selectAttr->id, 'attribute_id' => $selectAttr->id,
'value' => 'G', // Invalid value 'value' => 'G', // Invalid value
] ],
] ],
]); ]);
} }
public function test_it_returns_product_detail_with_variants_and_selected_variant_resource(): void public function test_it_returns_product_detail_with_variant_mapping_and_default_selected_variant(): void
{ {
// 1. Create a product
$product = Product::create([ $product = Product::create([
'tenant_codigo' => $this->tenant->codigo, 'tenant_codigo' => $this->tenant->codigo,
'categoria_id' => 1, 'categoria_id' => 1,
@@ -399,73 +404,202 @@ class ProductControllerTest extends TestCase
'nombre' => 'Test Product Show', 'nombre' => 'Test Product Show',
'precio' => 100.00, 'precio' => 100.00,
]); ]);
$productAttributes = $this->syncVariantAttributes($product);
// Associate attributes to product
$product->attributes()->sync([$this->sizeAttr->id, $this->colorAttr->id]);
// 2. Create variant
$variant = $product->createVariant([ $variant = $product->createVariant([
'slug' => 'test-product-show-s-azul', 'stock' => 0,
'nombre' => 'Test Product Show S Azul',
'stock' => 10,
'precio' => 105.00,
'definitions' => [ 'definitions' => [
[ [
'attribute_id' => $this->sizeAttr->id, 'products_attribute_id' => $productAttributes['size']->id,
'value' => 'S', 'value' => 'S',
], ],
[ [
'attribute_id' => $this->colorAttr->id, 'products_attribute_id' => $productAttributes['color']->id,
'value' => 'Azul', 'value' => 'Azul',
], ],
], ],
]); ]);
// Attach an image to the variant $secondVariant = $product->createVariant([
$attachment = \App\Domains\Attachable\Models\Attachment::create([ 'stock' => 4,
'key' => (string) Str::uuid(), 'definitions' => [
'path' => 'attachments/variant-img.png', [
'filename' => 'variant-img.png', 'products_attribute_id' => $productAttributes['size']->id,
'type' => \App\Domains\Attachable\Enums\AttachmentType::Image, 'value' => '38',
'mime_type' => 'image/png', ],
[
'products_attribute_id' => $productAttributes['color']->id,
'value' => 'Rojo',
],
],
]); ]);
$variant->attachments()->attach($attachment->id); $variantAttachment = $this->createAttachment('attachments/selected-variant.png');
$secondVariant->attachments()->attach($variantAttachment->id);
// 3. Request product show detail
$response = $this->getJson("/api/tenants/{$this->tenant->codigo}/productos/{$product->id}"); $response = $this->getJson("/api/tenants/{$this->tenant->codigo}/productos/{$product->id}");
$response->assertOk(); $response->assertOk();
// 4. Assert selected variant resource structure and data
$response->assertJsonStructure([ $response->assertJsonStructure([
'data' => [ 'data' => [
'id', 'id',
'nombre', 'nombre',
'attributes',
'variants_map' => [
'*' => [
'variant_id',
'stock',
'attributes' => [
'talle',
'color',
],
],
],
'variant' => [ 'variant' => [
'id', 'id',
'producto_id',
'stock', 'stock',
'definitions',
'images', 'images',
'definitions' => [
'*' => [
'id',
'producto_variante_id',
'products_attribute_id',
'attribute_id',
'value',
'attribute',
'metadata',
],
],
], ],
], ],
]); ]);
$response->assertJsonPath('data.variant.id', $variant->id); $response->assertJsonMissingPath('data.variants');
$response->assertJsonPath('data.variant.producto_id', $product->id); $response->assertJsonPath('data.variants_map.0.variant_id', $variant->id);
$response->assertJsonPath('data.variant.stock', 10); $response->assertJsonPath('data.variants_map.0.stock', 0);
$response->assertJsonPath('data.variants_map.0.attributes.talle', 'S');
$response->assertJsonPath('data.variants_map.0.attributes.color', 'Azul');
$response->assertJsonPath('data.variants_map.1.variant_id', $secondVariant->id);
$response->assertJsonPath('data.variants_map.1.stock', 4);
$response->assertJsonPath('data.variants_map.1.attributes.talle', '38');
$response->assertJsonPath('data.variants_map.1.attributes.color', 'Rojo');
$response->assertJsonCount(2, 'data.variants_map');
$response->assertJsonPath('data.variant.id', $secondVariant->id);
$response->assertJsonPath('data.variant.stock', 4);
$response->assertJsonPath('data.variant.definitions.talle', '38');
$response->assertJsonPath('data.variant.definitions.color', 'Rojo');
$response->assertJsonCount(1, 'data.variant.images'); $response->assertJsonCount(1, 'data.variant.images');
$response->assertJsonCount(2, 'data.variant.definitions'); $this->assertStringContainsString($variantAttachment->path, $response->json('data.variant.images.0'));
}
public function test_it_returns_requested_variant_in_product_detail(): void
{
$product = Product::create([
'tenant_codigo' => $this->tenant->codigo,
'categoria_id' => 1,
'slug' => 'test-product-requested-variant',
'nombre' => 'Test Product Requested Variant',
'precio' => 100.00,
]);
$productAttributes = $this->syncVariantAttributes($product);
$firstVariant = $product->createVariant([
'stock' => 5,
'definitions' => [
[
'products_attribute_id' => $productAttributes['size']->id,
'value' => 'S',
],
],
]);
$secondVariant = $product->createVariant([
'stock' => 7,
'definitions' => [
[
'products_attribute_id' => $productAttributes['size']->id,
'value' => '38',
],
],
]);
$response = $this->getJson("/api/tenants/{$this->tenant->codigo}/productos/{$product->id}?variant_id={$firstVariant->id}");
$response->assertOk();
$response->assertJsonPath('data.variant.id', $firstVariant->id);
$response->assertJsonPath('data.variant.stock', 5);
$response->assertJsonPath('data.variants_map.1.variant_id', $secondVariant->id);
}
public function test_it_rejects_product_detail_variant_id_from_another_product(): void
{
$product = Product::create([
'tenant_codigo' => $this->tenant->codigo,
'categoria_id' => 1,
'slug' => 'test-product-invalid-variant',
'nombre' => 'Test Product Invalid Variant',
'precio' => 100.00,
]);
$otherProduct = Product::create([
'tenant_codigo' => $this->tenant->codigo,
'categoria_id' => 1,
'slug' => 'test-product-other-variant',
'nombre' => 'Test Product Other Variant',
'precio' => 100.00,
]);
$otherVariant = $otherProduct->variants()->create(['stock' => 3]);
$response = $this->getJson("/api/tenants/{$this->tenant->codigo}/productos/{$product->id}?variant_id={$otherVariant->id}");
$response->assertNotFound();
}
public function test_selected_variant_images_fall_back_to_product_images(): void
{
$product = Product::create([
'tenant_codigo' => $this->tenant->codigo,
'categoria_id' => 1,
'slug' => 'test-product-fallback-images',
'nombre' => 'Test Product Fallback Images',
'precio' => 100.00,
]);
$productAttributes = $this->syncVariantAttributes($product);
$productAttachment = $this->createAttachment('attachments/product-fallback.png');
$product->attachments()->attach($productAttachment->id);
$variant = $product->createVariant([
'stock' => 6,
'definitions' => [
[
'products_attribute_id' => $productAttributes['size']->id,
'value' => 'S',
],
],
]);
$response = $this->getJson("/api/tenants/{$this->tenant->codigo}/productos/{$product->id}");
$response->assertOk();
$response->assertJsonPath('data.variant.id', $variant->id);
$response->assertJsonCount(1, 'data.variant.images');
$this->assertStringContainsString($productAttachment->path, $response->json('data.variant.images.0'));
}
/**
* @return array{size: ProductAttribute, color: ProductAttribute}
*/
private function syncVariantAttributes(Product $product): array
{
$product->attributes()->sync([$this->sizeAttr->id, $this->colorAttr->id]);
return [
'size' => $product->productAttributes()
->where('attribute_id', $this->sizeAttr->id)
->firstOrFail(),
'color' => $product->productAttributes()
->where('attribute_id', $this->colorAttr->id)
->firstOrFail(),
];
}
private function createAttachment(string $path): Attachment
{
return Attachment::create([
'key' => (string) Str::uuid(),
'path' => $path,
'filename' => basename($path),
'type' => AttachmentType::Image,
'mime_type' => 'image/png',
]);
} }
protected function createTenant(string $codigo, string $nombre, string $dominio): Tenant protected function createTenant(string $codigo, string $nombre, string $dominio): Tenant
@@ -473,18 +607,18 @@ class ProductControllerTest extends TestCase
$hdrKey = (string) Str::uuid(); $hdrKey = (string) Str::uuid();
$ftrKey = (string) Str::uuid(); $ftrKey = (string) Str::uuid();
$headerAttachment = \App\Domains\Attachable\Models\Attachment::create([ $headerAttachment = Attachment::create([
'key' => $hdrKey, 'key' => $hdrKey,
'path' => 'tenants/'.$hdrKey.'.png', 'path' => 'tenants/'.$hdrKey.'.png',
'filename' => 'logo_header.png', 'filename' => 'logo_header.png',
'type' => \App\Domains\Attachable\Enums\AttachmentType::Image, 'type' => AttachmentType::Image,
'mime_type' => 'image/png', 'mime_type' => 'image/png',
]); ]);
$footerAttachment = \App\Domains\Attachable\Models\Attachment::create([ $footerAttachment = Attachment::create([
'key' => $ftrKey, 'key' => $ftrKey,
'path' => 'tenants/'.$ftrKey.'.png', 'path' => 'tenants/'.$ftrKey.'.png',
'filename' => 'logo_footer.png', 'filename' => 'logo_footer.png',
'type' => \App\Domains\Attachable\Enums\AttachmentType::Image, 'type' => AttachmentType::Image,
'mime_type' => 'image/png', 'mime_type' => 'image/png',
]); ]);