feat: implement product creation workflow with variants, attribute definitions, and validation logic
This commit is contained in:
103
app/Domains/Catalog/Controllers/AttributeController.php
Normal file
103
app/Domains/Catalog/Controllers/AttributeController.php
Normal file
@@ -0,0 +1,103 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Catalog\Controllers;
|
||||
|
||||
use App\Domains\Catalog\Models\Attribute;
|
||||
use App\Domains\Catalog\Requests\StoreAttributeRequest;
|
||||
use App\Domains\Catalog\Requests\UpdateAttributeRequest;
|
||||
use App\Domains\Catalog\Resources\AttributeResource;
|
||||
use App\Domains\Shared\Enums\FieldType;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Response;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
|
||||
|
||||
class AttributeController extends Controller
|
||||
{
|
||||
public function index(Tenant $tenant): JsonResponse
|
||||
{
|
||||
$query = Attribute::query()
|
||||
->where('tenant_codigo', $tenant->codigo)
|
||||
->with('options')
|
||||
->latest();
|
||||
|
||||
return AttributeResource::collection($query->paginateFromRequest())->response();
|
||||
}
|
||||
|
||||
public function store(StoreAttributeRequest $request, Tenant $tenant): JsonResponse
|
||||
{
|
||||
$attribute = DB::transaction(function () use ($request, $tenant): Attribute {
|
||||
$validated = $request->validated();
|
||||
$options = $validated['options'] ?? [];
|
||||
unset($validated['options']);
|
||||
|
||||
$type = FieldType::from((string) $validated['type']);
|
||||
if (! $type->supportsOptions()) {
|
||||
$validated['metadata_schema'] = null;
|
||||
$options = [];
|
||||
}
|
||||
|
||||
/** @var Attribute $attribute */
|
||||
$attribute = Attribute::query()->create([
|
||||
...$validated,
|
||||
'tenant_codigo' => $tenant->codigo,
|
||||
]);
|
||||
$attribute->options()->createMany($options);
|
||||
|
||||
return $attribute->load('options');
|
||||
});
|
||||
|
||||
return AttributeResource::make($attribute)->response()->setStatusCode(201);
|
||||
}
|
||||
|
||||
public function show(Tenant $tenant, Attribute $attribute): AttributeResource
|
||||
{
|
||||
$attribute = $this->resolveScopedAttribute($tenant, $attribute);
|
||||
|
||||
return AttributeResource::make($attribute->load('options'));
|
||||
}
|
||||
|
||||
public function update(UpdateAttributeRequest $request, Tenant $tenant, Attribute $attribute): AttributeResource
|
||||
{
|
||||
$attribute = $this->resolveScopedAttribute($tenant, $attribute);
|
||||
|
||||
$attribute = DB::transaction(function () use ($request, $attribute): Attribute {
|
||||
$validated = $request->validated();
|
||||
$options = $validated['options'] ?? [];
|
||||
unset($validated['options']);
|
||||
|
||||
$type = FieldType::from((string) $validated['type']);
|
||||
if (! $type->supportsOptions()) {
|
||||
$validated['metadata_schema'] = null;
|
||||
$options = [];
|
||||
}
|
||||
|
||||
$attribute->update($validated);
|
||||
$attribute->options()->delete();
|
||||
$attribute->options()->createMany($options);
|
||||
|
||||
return $attribute->load('options');
|
||||
});
|
||||
|
||||
return AttributeResource::make($attribute);
|
||||
}
|
||||
|
||||
public function destroy(Tenant $tenant, Attribute $attribute): Response
|
||||
{
|
||||
$attribute = $this->resolveScopedAttribute($tenant, $attribute);
|
||||
$attribute->delete();
|
||||
|
||||
return response()->noContent();
|
||||
}
|
||||
|
||||
protected function resolveScopedAttribute(Tenant $tenant, Attribute $attribute): Attribute
|
||||
{
|
||||
if ($attribute->tenant_codigo !== $tenant->codigo) {
|
||||
throw new NotFoundHttpException('Attribute not found for tenant.');
|
||||
}
|
||||
|
||||
return $attribute;
|
||||
}
|
||||
}
|
||||
@@ -1,103 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Domains\Catalog\Controllers;
|
||||
|
||||
use App\Domains\Catalog\Models\ProductAttribute;
|
||||
use App\Domains\Catalog\Requests\StoreProductAttributeRequest;
|
||||
use App\Domains\Catalog\Requests\UpdateProductAttributeRequest;
|
||||
use App\Domains\Catalog\Resources\ProductAttributeResource;
|
||||
use App\Domains\Shared\Enums\FieldType;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
use Illuminate\Http\Response;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
use Symfony\Component\HttpKernel\Exception\NotFoundHttpException;
|
||||
|
||||
class ProductAttributeController extends Controller
|
||||
{
|
||||
public function index(Tenant $tenant): JsonResponse
|
||||
{
|
||||
$query = ProductAttribute::query()
|
||||
->where('tenant_codigo', $tenant->codigo)
|
||||
->with('options')
|
||||
->latest();
|
||||
|
||||
return ProductAttributeResource::collection($query->paginateFromRequest())->response();
|
||||
}
|
||||
|
||||
public function store(StoreProductAttributeRequest $request, Tenant $tenant): JsonResponse
|
||||
{
|
||||
$attribute = DB::transaction(function () use ($request, $tenant): ProductAttribute {
|
||||
$validated = $request->validated();
|
||||
$options = $validated['options'] ?? [];
|
||||
unset($validated['options']);
|
||||
|
||||
$type = FieldType::from((string) $validated['type']);
|
||||
if (! $type->supportsOptions()) {
|
||||
$validated['metadata_schema'] = null;
|
||||
$options = [];
|
||||
}
|
||||
|
||||
/** @var ProductAttribute $attribute */
|
||||
$attribute = ProductAttribute::query()->create([
|
||||
...$validated,
|
||||
'tenant_codigo' => $tenant->codigo,
|
||||
]);
|
||||
$attribute->options()->createMany($options);
|
||||
|
||||
return $attribute->load('options');
|
||||
});
|
||||
|
||||
return ProductAttributeResource::make($attribute)->response()->setStatusCode(201);
|
||||
}
|
||||
|
||||
public function show(Tenant $tenant, ProductAttribute $productAttribute): ProductAttributeResource
|
||||
{
|
||||
$productAttribute = $this->resolveScopedAttribute($tenant, $productAttribute);
|
||||
|
||||
return ProductAttributeResource::make($productAttribute->load('options'));
|
||||
}
|
||||
|
||||
public function update(UpdateProductAttributeRequest $request, Tenant $tenant, ProductAttribute $productAttribute): ProductAttributeResource
|
||||
{
|
||||
$productAttribute = $this->resolveScopedAttribute($tenant, $productAttribute);
|
||||
|
||||
$productAttribute = DB::transaction(function () use ($request, $productAttribute): ProductAttribute {
|
||||
$validated = $request->validated();
|
||||
$options = $validated['options'] ?? [];
|
||||
unset($validated['options']);
|
||||
|
||||
$type = FieldType::from((string) $validated['type']);
|
||||
if (! $type->supportsOptions()) {
|
||||
$validated['metadata_schema'] = null;
|
||||
$options = [];
|
||||
}
|
||||
|
||||
$productAttribute->update($validated);
|
||||
$productAttribute->options()->delete();
|
||||
$productAttribute->options()->createMany($options);
|
||||
|
||||
return $productAttribute->load('options');
|
||||
});
|
||||
|
||||
return ProductAttributeResource::make($productAttribute);
|
||||
}
|
||||
|
||||
public function destroy(Tenant $tenant, ProductAttribute $productAttribute): Response
|
||||
{
|
||||
$productAttribute = $this->resolveScopedAttribute($tenant, $productAttribute);
|
||||
$productAttribute->delete();
|
||||
|
||||
return response()->noContent();
|
||||
}
|
||||
|
||||
protected function resolveScopedAttribute(Tenant $tenant, ProductAttribute $attribute): ProductAttribute
|
||||
{
|
||||
if ($attribute->tenant_codigo !== $tenant->codigo) {
|
||||
throw new NotFoundHttpException('Product attribute not found for tenant.');
|
||||
}
|
||||
|
||||
return $attribute;
|
||||
}
|
||||
}
|
||||
@@ -6,6 +6,7 @@ use App\Domains\Catalog\Models\Product;
|
||||
use App\Domains\Catalog\Requests\StoreProductRequest;
|
||||
use App\Domains\Catalog\Requests\UpdateProductRequest;
|
||||
use App\Domains\Catalog\Resources\ProductResource;
|
||||
use App\Domains\Catalog\Services\ProductService;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use App\Http\Controllers\Controller;
|
||||
use Illuminate\Http\JsonResponse;
|
||||
@@ -21,12 +22,9 @@ class ProductController extends Controller
|
||||
)->response();
|
||||
}
|
||||
|
||||
public function store(StoreProductRequest $request, Tenant $tenant): JsonResponse
|
||||
public function store(StoreProductRequest $request, Tenant $tenant, ProductService $productService): JsonResponse
|
||||
{
|
||||
$product = Product::query()->create([
|
||||
...$request->validated(),
|
||||
'tenant_codigo' => $tenant->codigo,
|
||||
]);
|
||||
$product = $productService->createProductWithVariants($tenant, $request->validated());
|
||||
|
||||
return ProductResource::make($product)->response()->setStatusCode(201);
|
||||
}
|
||||
@@ -35,13 +33,13 @@ class ProductController extends Controller
|
||||
{
|
||||
$producto = $this->resolveScopedProduct($tenant, $producto);
|
||||
|
||||
return ProductResource::make($producto);
|
||||
return ProductResource::make($producto->load('variants.definitions.attribute'));
|
||||
}
|
||||
|
||||
public function update(UpdateProductRequest $request, Tenant $tenant, Product $producto): ProductResource
|
||||
public function update(UpdateProductRequest $request, Tenant $tenant, Product $producto, ProductService $productService): ProductResource
|
||||
{
|
||||
$producto = $this->resolveScopedProduct($tenant, $producto);
|
||||
$producto->update($request->validated());
|
||||
$producto = $productService->updateProductWithVariants($producto, $request->validated());
|
||||
|
||||
return ProductResource::make($producto);
|
||||
}
|
||||
|
||||
@@ -18,11 +18,11 @@ use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
'metadata_schema',
|
||||
'type',
|
||||
])]
|
||||
class ProductAttribute extends Model
|
||||
class Attribute extends Model
|
||||
{
|
||||
use HasFactory;
|
||||
|
||||
protected $table = 'productos_attributes';
|
||||
protected $table = 'attribute';
|
||||
|
||||
/**
|
||||
* @return array<string, string>
|
||||
@@ -45,11 +45,11 @@ class ProductAttribute extends Model
|
||||
}
|
||||
|
||||
/**
|
||||
* @return HasMany<ProductAttributeOption, $this>
|
||||
* @return HasMany<AttributeOption, $this>
|
||||
*/
|
||||
public function options(): HasMany
|
||||
{
|
||||
return $this->hasMany(ProductAttributeOption::class, 'attribute_id')->orderBy('sort_order');
|
||||
return $this->hasMany(AttributeOption::class, 'attribute_id')->orderBy('sort_order');
|
||||
}
|
||||
|
||||
/**
|
||||
@@ -14,7 +14,7 @@ use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
'sort_order',
|
||||
'metadata',
|
||||
])]
|
||||
class ProductAttributeOption extends Model
|
||||
class AttributeOption extends Model
|
||||
{
|
||||
use HasFactory;
|
||||
|
||||
@@ -32,10 +32,10 @@ class ProductAttributeOption extends Model
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BelongsTo<ProductAttribute, $this>
|
||||
* @return BelongsTo<Attribute, $this>
|
||||
*/
|
||||
public function attribute(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(ProductAttribute::class, 'attribute_id');
|
||||
return $this->belongsTo(Attribute::class, 'attribute_id');
|
||||
}
|
||||
}
|
||||
@@ -7,6 +7,7 @@ use Illuminate\Database\Eloquent\Attributes\Fillable;
|
||||
use Illuminate\Database\Eloquent\Factories\HasFactory;
|
||||
use Illuminate\Database\Eloquent\Model;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
||||
use Illuminate\Database\Eloquent\Relations\BelongsToMany;
|
||||
use Illuminate\Database\Eloquent\Relations\HasMany;
|
||||
|
||||
#[Fillable([
|
||||
@@ -46,4 +47,17 @@ class Product extends Model
|
||||
{
|
||||
return $this->hasMany(ProductVariant::class, 'producto_id');
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BelongsToMany<Attribute, $this>
|
||||
*/
|
||||
public function attributes(): BelongsToMany
|
||||
{
|
||||
return $this->belongsToMany(
|
||||
Attribute::class,
|
||||
'products_attributes',
|
||||
'product_id',
|
||||
'attribute_id'
|
||||
)->withTimestamps();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -16,7 +16,7 @@ class ProductVariantDefinition extends Model
|
||||
{
|
||||
use HasFactory;
|
||||
|
||||
protected $table = 'productos_variantes_definiciones';
|
||||
protected $table = 'productos_variantes_values';
|
||||
|
||||
/**
|
||||
* @return BelongsTo<ProductVariant, $this>
|
||||
@@ -27,10 +27,10 @@ class ProductVariantDefinition extends Model
|
||||
}
|
||||
|
||||
/**
|
||||
* @return BelongsTo<ProductAttribute, $this>
|
||||
* @return BelongsTo<Attribute, $this>
|
||||
*/
|
||||
public function attribute(): BelongsTo
|
||||
{
|
||||
return $this->belongsTo(ProductAttribute::class, 'attribute_id');
|
||||
return $this->belongsTo(Attribute::class, 'attribute_id');
|
||||
}
|
||||
}
|
||||
|
||||
@@ -7,7 +7,7 @@ use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Illuminate\Validation\Validator;
|
||||
|
||||
class StoreProductAttributeRequest extends FormRequest
|
||||
class StoreAttributeRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
@@ -24,7 +24,7 @@ class StoreProductAttributeRequest extends FormRequest
|
||||
'required',
|
||||
'string',
|
||||
'max:255',
|
||||
Rule::unique('productos_attributes', 'codigo')->where(
|
||||
Rule::unique('attribute', 'codigo')->where(
|
||||
fn ($query) => $query->where('tenant_codigo', $this->route('tenant')?->codigo)
|
||||
),
|
||||
],
|
||||
@@ -23,6 +23,38 @@ class StoreProductRequest extends FormRequest
|
||||
'nombre' => ['required', 'string', 'max:255'],
|
||||
'descripcion' => ['nullable', 'string'],
|
||||
'precio' => ['required', 'numeric', 'min:0'],
|
||||
'attribute_ids' => ['sometimes', 'array'],
|
||||
'attribute_ids.*' => [
|
||||
'required',
|
||||
'integer',
|
||||
Rule::exists('attribute', 'id')->where(
|
||||
fn ($query) => $query->where('tenant_codigo', $this->route('tenant')?->codigo)
|
||||
),
|
||||
],
|
||||
'variants' => ['sometimes', 'array'],
|
||||
'variants.*.slug' => ['nullable', 'string', 'max:255'],
|
||||
'variants.*.nombre' => ['nullable', 'string', 'max:255'],
|
||||
'variants.*.stock' => ['sometimes', 'integer', 'min:0'],
|
||||
'variants.*.descripcion' => ['nullable', 'string'],
|
||||
'variants.*.precio' => ['required', 'numeric', 'min:0'],
|
||||
'variants.*.definitions' => [
|
||||
'sometimes',
|
||||
'array',
|
||||
function ($attribute, $value, $fail) {
|
||||
$attributeIds = array_column($value, 'attribute_id');
|
||||
if (count($attributeIds) !== count(array_unique($attributeIds))) {
|
||||
$fail('The definitions must have distinct attribute ids.');
|
||||
}
|
||||
}
|
||||
],
|
||||
'variants.*.definitions.*.attribute_id' => [
|
||||
'required',
|
||||
'integer',
|
||||
Rule::exists('attribute', 'id')->where(
|
||||
fn ($query) => $query->where('tenant_codigo', $this->route('tenant')?->codigo)
|
||||
),
|
||||
],
|
||||
'variants.*.definitions.*.value' => ['nullable', 'string'],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -42,7 +42,7 @@ class StoreProductVariantRequest extends FormRequest
|
||||
'required',
|
||||
'integer',
|
||||
'distinct',
|
||||
Rule::exists('productos_attributes', 'id')->where(
|
||||
Rule::exists('attribute', 'id')->where(
|
||||
fn ($query) => $query->where('tenant_codigo', $this->route('tenant')?->codigo)
|
||||
),
|
||||
],
|
||||
|
||||
@@ -2,13 +2,13 @@
|
||||
|
||||
namespace App\Domains\Catalog\Requests;
|
||||
|
||||
use App\Domains\Catalog\Models\ProductAttribute;
|
||||
use App\Domains\Catalog\Models\Attribute;
|
||||
use App\Domains\Shared\Enums\FieldType;
|
||||
use Illuminate\Foundation\Http\FormRequest;
|
||||
use Illuminate\Validation\Rule;
|
||||
use Illuminate\Validation\Validator;
|
||||
|
||||
class UpdateProductAttributeRequest extends FormRequest
|
||||
class UpdateAttributeRequest extends FormRequest
|
||||
{
|
||||
public function authorize(): bool
|
||||
{
|
||||
@@ -20,15 +20,15 @@ class UpdateProductAttributeRequest extends FormRequest
|
||||
*/
|
||||
public function rules(): array
|
||||
{
|
||||
/** @var ProductAttribute|null $attribute */
|
||||
$attribute = $this->route('productAttribute');
|
||||
/** @var Attribute|null $attribute */
|
||||
$attribute = $this->route('attribute');
|
||||
|
||||
return [
|
||||
'codigo' => [
|
||||
'required',
|
||||
'string',
|
||||
'max:255',
|
||||
Rule::unique('productos_attributes', 'codigo')
|
||||
Rule::unique('attribute', 'codigo')
|
||||
->ignore($attribute?->id)
|
||||
->where(fn ($query) => $query->where('tenant_codigo', $attribute?->tenant_codigo)),
|
||||
],
|
||||
@@ -32,6 +32,45 @@ class UpdateProductRequest extends FormRequest
|
||||
'nombre' => ['required', 'string', 'max:255'],
|
||||
'descripcion' => ['nullable', 'string'],
|
||||
'precio' => ['required', 'numeric', 'min:0'],
|
||||
'attribute_ids' => ['sometimes', 'array'],
|
||||
'attribute_ids.*' => [
|
||||
'required',
|
||||
'integer',
|
||||
Rule::exists('attribute', 'id')->where(
|
||||
fn ($query) => $query->where('tenant_codigo', $this->route('tenant')?->codigo)
|
||||
),
|
||||
],
|
||||
'variants' => ['sometimes', 'array'],
|
||||
'variants.*.id' => [
|
||||
'sometimes',
|
||||
'integer',
|
||||
Rule::exists('productos_variantes', 'id')->where(
|
||||
fn ($query) => $query->where('producto_id', $product?->id)
|
||||
),
|
||||
],
|
||||
'variants.*.slug' => ['nullable', 'string', 'max:255'],
|
||||
'variants.*.nombre' => ['nullable', 'string', 'max:255'],
|
||||
'variants.*.stock' => ['sometimes', 'integer', 'min:0'],
|
||||
'variants.*.descripcion' => ['nullable', 'string'],
|
||||
'variants.*.precio' => ['required', 'numeric', 'min:0'],
|
||||
'variants.*.definitions' => [
|
||||
'sometimes',
|
||||
'array',
|
||||
function ($attribute, $value, $fail) {
|
||||
$attributeIds = array_column($value, 'attribute_id');
|
||||
if (count($attributeIds) !== count(array_unique($attributeIds))) {
|
||||
$fail('The definitions must have distinct attribute ids.');
|
||||
}
|
||||
}
|
||||
],
|
||||
'variants.*.definitions.*.attribute_id' => [
|
||||
'required',
|
||||
'integer',
|
||||
Rule::exists('attribute', 'id')->where(
|
||||
fn ($query) => $query->where('tenant_codigo', $this->route('tenant')?->codigo)
|
||||
),
|
||||
],
|
||||
'variants.*.definitions.*.value' => ['nullable', 'string'],
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -46,7 +46,7 @@ class UpdateProductVariantRequest extends FormRequest
|
||||
'required',
|
||||
'integer',
|
||||
'distinct',
|
||||
Rule::exists('productos_attributes', 'id')->where(
|
||||
Rule::exists('attribute', 'id')->where(
|
||||
fn ($query) => $query->where('tenant_codigo', $this->route('tenant')?->codigo)
|
||||
),
|
||||
],
|
||||
|
||||
@@ -6,9 +6,9 @@ use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
/**
|
||||
* @mixin \App\Domains\Catalog\Models\ProductAttributeOption
|
||||
* @mixin \App\Domains\Catalog\Models\AttributeOption
|
||||
*/
|
||||
class ProductAttributeOptionResource extends JsonResource
|
||||
class AttributeOptionResource extends JsonResource
|
||||
{
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
@@ -6,9 +6,9 @@ use Illuminate\Http\Request;
|
||||
use Illuminate\Http\Resources\Json\JsonResource;
|
||||
|
||||
/**
|
||||
* @mixin \App\Domains\Catalog\Models\ProductAttribute
|
||||
* @mixin \App\Domains\Catalog\Models\Attribute
|
||||
*/
|
||||
class ProductAttributeResource extends JsonResource
|
||||
class AttributeResource extends JsonResource
|
||||
{
|
||||
/**
|
||||
* @return array<string, mixed>
|
||||
@@ -23,7 +23,7 @@ class ProductAttributeResource extends JsonResource
|
||||
'is_required' => $this->is_required,
|
||||
'metadata_schema' => $this->metadata_schema,
|
||||
'type' => $this->type?->value ?? $this->type,
|
||||
'options' => ProductAttributeOptionResource::collection($this->whenLoaded('options')),
|
||||
'options' => AttributeOptionResource::collection($this->whenLoaded('options')),
|
||||
];
|
||||
}
|
||||
}
|
||||
@@ -23,6 +23,7 @@ class ProductResource extends JsonResource
|
||||
'nombre' => $this->nombre,
|
||||
'descripcion' => $this->descripcion,
|
||||
'precio' => $this->precio,
|
||||
'variants' => ProductVariantResource::collection($this->whenLoaded('variants')),
|
||||
'created_at' => $this->created_at,
|
||||
'updated_at' => $this->updated_at,
|
||||
];
|
||||
|
||||
@@ -20,7 +20,7 @@ class ProductVariantDefinitionResource extends JsonResource
|
||||
'producto_variante_id' => $this->producto_variante_id,
|
||||
'attribute_id' => $this->attribute_id,
|
||||
'value' => $this->value,
|
||||
'attribute' => ProductAttributeResource::make($this->whenLoaded('attribute')),
|
||||
'attribute' => AttributeResource::make($this->whenLoaded('attribute')),
|
||||
];
|
||||
}
|
||||
}
|
||||
|
||||
@@ -2,7 +2,114 @@
|
||||
|
||||
namespace App\Domains\Catalog\Services;
|
||||
|
||||
use App\Domains\Catalog\Models\Product;
|
||||
use App\Domains\Tenant\Models\Tenant;
|
||||
use Illuminate\Support\Facades\DB;
|
||||
|
||||
class ProductService
|
||||
{
|
||||
// Reserved for product domain business logic.
|
||||
/**
|
||||
* Create a product along with its variants and variant definitions.
|
||||
*
|
||||
* @param array<string, mixed> $data
|
||||
*/
|
||||
public function createProductWithVariants(Tenant $tenant, array $data): Product
|
||||
{
|
||||
return DB::transaction(function () use ($tenant, $data) {
|
||||
$variantsData = $data['variants'] ?? [];
|
||||
unset($data['variants']);
|
||||
|
||||
$attributeIds = $data['attribute_ids'] ?? [];
|
||||
unset($data['attribute_ids']);
|
||||
|
||||
/** @var Product $product */
|
||||
$product = Product::query()->create([
|
||||
...$data,
|
||||
'tenant_codigo' => $tenant->codigo,
|
||||
]);
|
||||
|
||||
foreach ($variantsData as $variantData) {
|
||||
$definitions = $variantData['definitions'] ?? [];
|
||||
unset($variantData['definitions']);
|
||||
|
||||
$variant = $product->variants()->create($variantData);
|
||||
$variant->definitions()->createMany($definitions);
|
||||
}
|
||||
|
||||
$attributeIdsFromVariants = collect($variantsData)->flatMap(function ($variant) {
|
||||
return collect($variant['definitions'] ?? [])->pluck('attribute_id');
|
||||
})->unique()->toArray();
|
||||
|
||||
$allAttributeIds = array_unique(array_merge($attributeIds, $attributeIdsFromVariants));
|
||||
$product->attributes()->sync($allAttributeIds);
|
||||
|
||||
return $product->load(['variants.definitions.attribute', 'attributes']);
|
||||
});
|
||||
}
|
||||
|
||||
/**
|
||||
* Update a product along with its variants and variant definitions.
|
||||
*
|
||||
* @param array<string, mixed> $data
|
||||
*/
|
||||
public function updateProductWithVariants(Product $product, array $data): Product
|
||||
{
|
||||
return DB::transaction(function () use ($product, $data) {
|
||||
$hasVariants = array_key_exists('variants', $data);
|
||||
$variantsData = $data['variants'] ?? [];
|
||||
unset($data['variants']);
|
||||
|
||||
$hasAttributeIds = array_key_exists('attribute_ids', $data);
|
||||
$attributeIds = $data['attribute_ids'] ?? [];
|
||||
unset($data['attribute_ids']);
|
||||
|
||||
$product->update($data);
|
||||
|
||||
if ($hasVariants) {
|
||||
$existingVariantIds = $product->variants()->pluck('id')->toArray();
|
||||
$incomingVariantIds = [];
|
||||
|
||||
foreach ($variantsData as $variantData) {
|
||||
$definitions = $variantData['definitions'] ?? [];
|
||||
unset($variantData['definitions']);
|
||||
|
||||
$variantId = $variantData['id'] ?? null;
|
||||
|
||||
if ($variantId && in_array($variantId, $existingVariantIds)) {
|
||||
$variant = $product->variants()->findOrFail($variantId);
|
||||
$variant->update($variantData);
|
||||
$incomingVariantIds[] = (int) $variantId;
|
||||
} else {
|
||||
$variant = $product->variants()->create($variantData);
|
||||
$incomingVariantIds[] = $variant->id;
|
||||
}
|
||||
|
||||
$variant->definitions()->delete();
|
||||
$variant->definitions()->createMany($definitions);
|
||||
}
|
||||
|
||||
$variantsToDelete = array_diff($existingVariantIds, $incomingVariantIds);
|
||||
if (!empty($variantsToDelete)) {
|
||||
$product->variants()->whereIn('id', $variantsToDelete)->delete();
|
||||
}
|
||||
}
|
||||
|
||||
if ($hasAttributeIds || $hasVariants) {
|
||||
$explicitIds = $hasAttributeIds ? $attributeIds : $product->attributes()->pluck('attribute_id')->toArray();
|
||||
|
||||
$variantIds = $product->variants()->pluck('id')->toArray();
|
||||
$attributeIdsFromVariants = DB::table('productos_variantes_values')
|
||||
->whereIn('producto_variante_id', $variantIds)
|
||||
->pluck('attribute_id')
|
||||
->unique()
|
||||
->toArray();
|
||||
|
||||
$allAttributeIds = array_unique(array_merge($explicitIds, $attributeIdsFromVariants));
|
||||
$product->attributes()->sync($allAttributeIds);
|
||||
}
|
||||
|
||||
return $product->load(['variants.definitions.attribute', 'attributes']);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@
|
||||
use App\Domains\Catalog\Controllers\BrandController;
|
||||
use App\Domains\Catalog\Controllers\CategoryController;
|
||||
use App\Domains\Catalog\Controllers\ProductController;
|
||||
use App\Domains\Catalog\Controllers\ProductAttributeController;
|
||||
use App\Domains\Catalog\Controllers\AttributeController;
|
||||
use App\Domains\Catalog\Controllers\ProductVariantController;
|
||||
use Illuminate\Support\Facades\Route;
|
||||
|
||||
@@ -11,8 +11,7 @@ Route::prefix('tenants/{tenant:codigo}')->group(function (): void {
|
||||
Route::apiResource('marcas', BrandController::class)->parameters(['marcas' => 'marca']);
|
||||
Route::apiResource('categorias', CategoryController::class)->parameters(['categorias' => 'categoria']);
|
||||
Route::apiResource('productos', ProductController::class);
|
||||
Route::apiResource('product-attributes', ProductAttributeController::class)
|
||||
->parameters(['product-attributes' => 'productAttribute']);
|
||||
Route::apiResource('attributes', AttributeController::class);
|
||||
Route::apiResource('product-variants', ProductVariantController::class)
|
||||
->parameters(['product-variants' => 'productVariant']);
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user