refactor(catalog): Complete catalog refactor to simplify its data model and its querying.

source commits: refactor/catalog
This commit is contained in:
2026-07-21 09:23:19 -03:00
parent d3182fbd13
commit 29a2ca19a3
116 changed files with 5141 additions and 5217 deletions

View File

@@ -28,8 +28,10 @@ class CartController extends Controller
$result = $this->cartService->addItem(
$tenant,
$request,
$request->mappedBuyableType(),
(int) $request->validated('buyable_id'),
(int) $request->validated('catalog_item_id'),
$request->validated('variant_id') !== null
? (int) $request->validated('variant_id')
: null,
(int) $request->validated('cantidad'),
);

View File

@@ -3,9 +3,10 @@
namespace App\Domains\Cart\Models;
use App\Domains\Auth\Models\User;
use App\Domains\Bundle\Models\Bundle;
use App\Domains\Catalog\Models\ProductVariant;
use App\Domains\Shared\Contracts\Buyable;
use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Catalog\Models\Inventory;
use App\Domains\Catalog\Models\Variant;
use App\Domains\Catalog\Services\CatalogInventoryService;
use App\Domains\Tenant\Models\Tenant;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
@@ -65,15 +66,16 @@ class Cart extends Model
{
$items = $this->relationLoaded('items')
? $this->getRelation('items')
: $this->items()->with('buyable')->get();
: $this->items()->with(['catalogItem', 'variant'])->get();
return (float) $items->reduce(
fn (float $carry, $item): float => $carry + ($item->buyable?->getPrice() * $item->cantidad),
fn (float $carry, CartItem $item): float => $carry
+ (($item->selectedItem()?->getPrice() ?? 0) * $item->cantidad),
0.0,
);
}
public function addItem(string $buyableType, int $buyableId, int $quantity): CartItem
public function addItem(int $catalogItemId, ?int $variantId, int $quantity): CartItem
{
if ($quantity <= 0) {
throw ValidationException::withMessages([
@@ -81,10 +83,11 @@ class Cart extends Model
]);
}
return DB::transaction(function () use ($buyableType, $buyableId, $quantity): CartItem {
$buyable = $this->resolveScopedBuyable($buyableType, $buyableId, true);
$canonicalType = $buyable::class;
$availableQuantity = $buyable->availableQuantity();
return DB::transaction(function () use ($catalogItemId, $variantId, $quantity): CartItem {
self::query()->whereKey($this->getKey())->lockForUpdate()->firstOrFail();
$selectedItem = $this->resolveScopedItem($catalogItemId, $variantId, true);
$inventoryService = app(CatalogInventoryService::class);
$availableQuantity = $inventoryService->availableQuantity($selectedItem);
if ($availableQuantity !== null && $availableQuantity < $quantity) {
throw ValidationException::withMessages([
@@ -94,15 +97,15 @@ class Cart extends Model
/** @var CartItem|null $item */
$item = $this->items()
->where('buyable_type', $canonicalType)
->where('buyable_id', $buyable->getKey())
->where('catalog_item_id', $catalogItemId)
->where('variant_id', $variantId)
->lockForUpdate()
->first();
if ($item === null) {
$item = $this->items()->create([
'buyable_type' => $canonicalType,
'buyable_id' => $buyable->getKey(),
'catalog_item_id' => $catalogItemId,
'variant_id' => $variantId,
'cantidad' => $quantity,
]);
} else {
@@ -110,7 +113,7 @@ class Cart extends Model
$item->save();
}
$buyable->reserveStock($quantity);
$inventoryService->reserve($selectedItem, $quantity);
return $item->fresh();
});
@@ -131,9 +134,14 @@ class Cart extends Model
->lockForUpdate()
->firstOrFail();
$buyable = $this->resolveScopedBuyable($item->buyable_type, $item->buyable_id, true);
$selectedItem = $this->resolveScopedItem(
$item->catalog_item_id,
$item->variant_id,
true,
);
$inventoryService = app(CatalogInventoryService::class);
$delta = $quantity - $item->cantidad;
$availableQuantity = $buyable->availableQuantity();
$availableQuantity = $inventoryService->availableQuantity($selectedItem);
if ($delta > 0 && $availableQuantity !== null && $availableQuantity < $delta) {
$maxAvailable = $availableQuantity + $item->cantidad;
@@ -146,11 +154,11 @@ class Cart extends Model
$item->save();
if ($delta > 0) {
$buyable->reserveStock($delta);
$inventoryService->reserve($selectedItem, $delta);
}
if ($delta < 0) {
$buyable->decrementReservedStock(abs($delta));
$inventoryService->release($selectedItem, abs($delta));
}
return $item->fresh();
@@ -166,45 +174,96 @@ class Cart extends Model
->lockForUpdate()
->firstOrFail();
$buyable = $this->resolveScopedBuyable($item->buyable_type, $item->buyable_id, true);
$buyable->decrementReservedStock($item->cantidad);
$selectedItem = $this->resolveScopedItem(
$item->catalog_item_id,
$item->variant_id,
true,
);
app(CatalogInventoryService::class)->release(
$selectedItem,
$item->cantidad,
);
$item->delete();
});
}
protected function resolveScopedBuyable(string $buyableType, int $buyableId, bool $lockForUpdate = false): Buyable
{
$buyableClass = $this->resolveBuyableClass($buyableType);
protected function resolveScopedItem(
int $catalogItemId,
?int $variantId,
bool $lockForUpdate = false,
): CatalogItem|Variant {
$catalogItemQuery = CatalogItem::query()
->whereKey($catalogItemId)
->where('tenant_code', $this->tenant_codigo);
if ($buyableClass === ProductVariant::class) {
$query = ProductVariant::query()
->whereKey($buyableId)
->whereHas('product', fn ($query) => $query->where('tenant_codigo', $this->tenant_codigo));
} else {
$query = Bundle::query()
->whereKey($buyableId)
->where('tenant_codigo', $this->tenant_codigo);
if ($lockForUpdate) {
$catalogItemQuery->lockForUpdate();
}
$catalogItem = $catalogItemQuery->first();
if ($catalogItem === null) {
throw new NotFoundHttpException('Catalog item not found for tenant.');
}
if ($catalogItem->isBundle()) {
if ($variantId !== null) {
throw ValidationException::withMessages([
'variant_id' => 'Un bundle no admite una variante.',
]);
}
if (! $catalogItem->bundleComponents()->exists()) {
throw ValidationException::withMessages([
'catalog_item_id' => 'El bundle no tiene componentes.',
]);
}
return $catalogItem;
}
if ($variantId === null) {
if ($catalogItem->inventory_id === null) {
throw ValidationException::withMessages([
'variant_id' => 'Debe seleccionar una variante para este ítem.',
]);
}
$inventory = $this->resolveInventory($catalogItem->inventory_id, $lockForUpdate);
$catalogItem->setRelation('inventory', $inventory);
return $catalogItem;
}
$variantQuery = Variant::query()
->whereKey($variantId)
->where('catalog_item_id', $catalogItem->id);
if ($lockForUpdate) {
$variantQuery->lockForUpdate();
}
$variant = $variantQuery->first();
if ($variant === null) {
throw new NotFoundHttpException('Variant not found for catalog item.');
}
$inventory = $this->resolveInventory($variant->inventory_id, $lockForUpdate);
$variant->setRelation('catalogItem', $catalogItem);
$variant->setRelation('inventory', $inventory);
return $variant;
}
protected function resolveInventory(int $inventoryId, bool $lockForUpdate): Inventory
{
$query = Inventory::query()->whereKey($inventoryId);
if ($lockForUpdate) {
$query->lockForUpdate();
}
$buyable = $query->first();
if ($buyable === null) {
throw new NotFoundHttpException('Buyable not found for tenant.');
}
return $buyable;
}
protected function resolveBuyableClass(string $buyableType): string
{
return match ($buyableType) {
'variant', ProductVariant::class => ProductVariant::class,
'bundle', Bundle::class => Bundle::class,
default => throw new \InvalidArgumentException('Invalid buyable type'),
};
return $query->firstOrFail();
}
}

View File

@@ -2,7 +2,8 @@
namespace App\Domains\Cart\Models;
use App\Domains\Catalog\Models\ProductVariant;
use App\Domains\Catalog\Models\CatalogItem;
use App\Domains\Catalog\Models\Variant;
use Illuminate\Database\Eloquent\Attributes\Fillable;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
@@ -10,8 +11,8 @@ use Illuminate\Database\Eloquent\Relations\BelongsTo;
#[Fillable([
'cart_id',
'buyable_id',
'buyable_type',
'catalog_item_id',
'variant_id',
'cantidad',
])]
class CartItem extends Model
@@ -24,8 +25,8 @@ class CartItem extends Model
{
return [
'cart_id' => 'integer',
'buyable_id' => 'integer',
'buyable_type' => 'string',
'catalog_item_id' => 'integer',
'variant_id' => 'integer',
'cantidad' => 'integer',
];
}
@@ -38,11 +39,20 @@ class CartItem extends Model
return $this->belongsTo(Cart::class, 'cart_id');
}
/**
* @return \Illuminate\Database\Eloquent\Relations\MorphTo
*/
public function buyable()
/** @return BelongsTo<CatalogItem, $this> */
public function catalogItem(): BelongsTo
{
return $this->morphTo();
return $this->belongsTo(CatalogItem::class);
}
/** @return BelongsTo<Variant, $this> */
public function variant(): BelongsTo
{
return $this->belongsTo(Variant::class);
}
public function selectedItem(): CatalogItem|Variant|null
{
return $this->variant ?? $this->catalogItem;
}
}

View File

@@ -2,8 +2,6 @@
namespace App\Domains\Cart\Requests;
use App\Domains\Bundle\Models\Bundle;
use App\Domains\Catalog\Models\ProductVariant;
use Illuminate\Foundation\Http\FormRequest;
use Illuminate\Validation\Rule;
@@ -19,19 +17,25 @@ class AddCartItemRequest extends FormRequest
*/
public function rules(): array
{
$tenantCode = $this->route('tenant')?->codigo;
return [
'buyable_type' => ['required', 'string', Rule::in(['variant', 'bundle'])],
'buyable_id' => ['required', 'integer'],
'catalog_item_id' => [
'required',
'integer',
Rule::exists('catalog_items', 'id')->where(
fn ($query) => $query->where('tenant_code', $tenantCode)
),
],
'variant_id' => [
'sometimes',
'nullable',
'integer',
Rule::exists('variantes', 'id')->where(
fn ($query) => $query->where('catalog_item_id', $this->input('catalog_item_id'))
),
],
'cantidad' => ['required', 'integer', 'min:1'],
];
}
public function mappedBuyableType(): string
{
return match ($this->input('buyable_type')) {
'variant' => ProductVariant::class,
'bundle' => Bundle::class,
default => throw new \InvalidArgumentException('Invalid buyable type'),
};
}
}

View File

@@ -18,8 +18,8 @@ class UpdateCartItemQuantityRequest extends FormRequest
{
return [
'cantidad' => ['required', 'integer', 'min:1'],
'buyable_type' => ['prohibited'],
'buyable_id' => ['prohibited'],
'catalog_item_id' => ['prohibited'],
'variant_id' => ['prohibited'],
];
}
}

View File

@@ -2,11 +2,12 @@
namespace App\Domains\Cart\Resources;
use App\Domains\Cart\Models\CartItem;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
/**
* @mixin \App\Domains\Cart\Models\CartItem
* @mixin CartItem
*/
class CartItemResource extends JsonResource
{
@@ -15,42 +16,30 @@ class CartItemResource extends JsonResource
*/
public function toArray(Request $request): array
{
/** @var \App\Domains\Shared\Contracts\Buyable|null $buyable */
$buyable = $this->buyable;
$productName = $buyable?->getName();
$precio = $buyable?->getPrice();
$selectedItem = $this->selectedItem();
$imageUrl = null;
if ($this->buyable_type === \App\Domains\Catalog\Models\ProductVariant::class && $buyable && $buyable->relationLoaded('attachments')) {
$firstAttachment = $buyable->attachments->first();
if ($firstAttachment) {
$imageUrl = $firstAttachment->getTemporaryUrl(1440);
}
if ($selectedItem?->relationLoaded('attachments')) {
$imageUrl = $selectedItem->attachments->first()?->getTemporaryUrl(1440);
}
if ($imageUrl === null && $this->catalogItem?->relationLoaded('attachments')) {
$imageUrl = $this->catalogItem->attachments->first()?->getTemporaryUrl(1440);
}
return [
'id' => $this->id,
'cantidad' => $this->cantidad,
'precio_unitario' => $this->formatMoney($precio),
'buyable_type' => $this->mapBuyableTypeToAlias($this->buyable_type),
'buyable_id' => $this->buyable_id,
'product' => $buyable === null ? null : [
'nombre' => $productName,
'precio_unitario' => $this->formatMoney($selectedItem?->getPrice()),
'catalog_item_id' => $this->catalog_item_id,
'variant_id' => $this->variant_id,
'product' => $selectedItem === null ? null : [
'nombre' => $selectedItem->getName(),
'imagen' => $imageUrl,
],
];
}
protected function mapBuyableTypeToAlias(?string $type): string
{
return match ($type) {
\App\Domains\Catalog\Models\ProductVariant::class => 'variant',
\App\Domains\Bundle\Models\Bundle::class => 'bundle',
default => 'unknown',
};
}
protected function formatMoney(float|int|string|null $amount): string
{
return number_format((float) ($amount ?? 0), 2, '.', '');

View File

@@ -21,7 +21,8 @@ class CartResource extends JsonResource
: collect();
$subtotal = $items->reduce(
fn (float $carry, $item): float => $carry + ((float) ($item->buyable?->getPrice() ?? 0) * $item->cantidad),
fn (float $carry, $item): float => $carry
+ ((float) ($item->selectedItem()?->getPrice() ?? 0) * $item->cantidad),
0.0,
);

View File

@@ -3,11 +3,8 @@
namespace App\Domains\Cart\Services;
use App\Domains\Auth\Models\User;
use App\Domains\Bundle\Models\Bundle;
use App\Domains\Cart\Models\Cart;
use App\Domains\Catalog\Models\ProductVariant;
use App\Domains\Tenant\Models\Tenant;
use Illuminate\Database\Eloquent\Relations\MorphTo;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;
@@ -36,12 +33,17 @@ class CartService
/**
* @return array{cart: Cart, guest_token: ?string}
*/
public function addItem(Tenant $tenant, Request $request, string $buyableType, int $buyableId, int $quantity): array
{
public function addItem(
Tenant $tenant,
Request $request,
int $catalogItemId,
?int $variantId,
int $quantity,
): array {
$resolvedIdentity = $this->resolveIdentity($request, true);
$identity = $resolvedIdentity['identity'];
$cart = $this->findOrCreateCart($tenant, $identity);
$cart->addItem($buyableType, $buyableId, $quantity);
$cart->addItem($catalogItemId, $variantId, $quantity);
return [
'cart' => $this->loadCart($cart),
@@ -97,16 +99,11 @@ class CartService
protected function loadCart(Cart $cart): Cart
{
return $cart->fresh()->load([
'items.buyable' => function (MorphTo $morphTo): void {
$morphTo->morphWith([
ProductVariant::class => [
'product',
'definitions.productAttribute.attribute',
'attachments',
],
Bundle::class => ['items.variant'],
]);
},
'items.catalogItem.attachments',
'items.catalogItem.inventory',
'items.variant.attachments',
'items.variant.inventory',
'items.variant.definitions.itemAttribute.attribute',
]);
}