feat: refactor cart and bundle handling to support Buyable interface for improved flexibility

This commit is contained in:
2026-07-14 16:41:34 -03:00
parent 562b48b3bd
commit ab042acf9b
11 changed files with 171 additions and 144 deletions

View File

@@ -10,7 +10,7 @@ use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Casts\Attribute;
use App\Domains\Shared\Contracts\Stockable;
use App\Domains\Shared\Contracts\Buyable;
#[Fillable([
'tenant_codigo',
@@ -18,7 +18,7 @@ use App\Domains\Shared\Contracts\Stockable;
'descripcion',
'precio',
])]
class Bundle extends Model implements Stockable
class Bundle extends Model implements Buyable
{
use HasFactory;
@@ -49,6 +49,16 @@ class Bundle extends Model implements Stockable
return $this->hasMany(BundleItem::class, 'bundle_id');
}
public function getPrice(): float
{
return (float) $this->precio;
}
public function getName(): string
{
return $this->nombre ?? 'Bundle';
}
public function incrementRealStock(int $amount): void
{
if ($amount < 0) {

View File

@@ -29,7 +29,8 @@ class CartController extends Controller
$result = $this->cartService->addItem(
$tenant,
$request,
(int) $request->validated('product_variant_id'),
$request->validated('buyable_type'),
(int) $request->validated('buyable_id'),
(int) $request->validated('cantidad'),
);
@@ -47,22 +48,24 @@ class CartController extends Controller
public function updateItemQuantity(
UpdateCartItemQuantityRequest $request,
Tenant $tenant,
ProductVariant $productVariant,
string $buyableType,
int $buyableId,
): CartResource {
return CartResource::make(
$this->cartService->updateItemQuantity(
$tenant,
$request,
$productVariant->getKey(),
$buyableType,
$buyableId,
(int) $request->validated('cantidad'),
)
)->additional(['message' => 'Cantidad de producto actualizada.']);
}
public function removeItem(Request $request, Tenant $tenant, ProductVariant $productVariant): CartResource
public function removeItem(Request $request, Tenant $tenant, string $buyableType, int $buyableId): CartResource
{
return CartResource::make(
$this->cartService->removeItem($tenant, $request, $productVariant->getKey())
$this->cartService->removeItem($tenant, $request, $buyableType, $buyableId)
)->additional(['message' => 'Producto eliminado del carrito.']);
}
}

View File

@@ -63,15 +63,15 @@ class Cart extends Model
{
$items = $this->relationLoaded('items')
? $this->getRelation('items')
: $this->items()->with('variant.product')->get();
: $this->items()->with('buyable')->get();
return (float) $items->reduce(
fn (float $carry, $item): float => $carry + ((float) ($item->variant?->product?->precio ?? 0) * $item->cantidad),
fn (float $carry, $item): float => $carry + ($item->buyable?->getPrice() * $item->cantidad),
0.0,
);
}
public function addItem(int $productVariantId, int $quantity): CartItem
public function addItem(string $buyableType, int $buyableId, int $quantity): CartItem
{
if ($quantity <= 0) {
throw ValidationException::withMessages([
@@ -79,24 +79,26 @@ class Cart extends Model
]);
}
return DB::transaction(function () use ($productVariantId, $quantity): CartItem {
$variant = $this->resolveScopedVariant($productVariantId, true);
return DB::transaction(function () use ($buyableType, $buyableId, $quantity): CartItem {
$buyable = $this->resolveScopedBuyable($buyableType, $buyableId, true);
if ($variant->stock_tecnico < $quantity) {
if ($buyable->stock_tecnico < $quantity) {
throw ValidationException::withMessages([
'cantidad' => "Stock insuficiente para la variante solicitada. Maximo disponible: {$variant->stock_tecnico}.",
'cantidad' => "Stock insuficiente para la variante/bundle solicitado. Maximo disponible: {$buyable->stock_tecnico}.",
]);
}
/** @var CartItem|null $item */
$item = $this->items()
->where('producto_variante_id', $variant->getKey())
->where('buyable_type', $buyableType)
->where('buyable_id', $buyable->getKey())
->lockForUpdate()
->first();
if ($item === null) {
$item = $this->items()->create([
'producto_variante_id' => $variant->getKey(),
'buyable_type' => $buyableType,
'buyable_id' => $buyable->getKey(),
'cantidad' => $quantity,
]);
} else {
@@ -104,13 +106,13 @@ class Cart extends Model
$item->save();
}
$variant->incrementReservedStock($quantity);
$buyable->incrementReservedStock($quantity);
return $item->fresh();
});
}
public function updateItem(int $productVariantId, int $quantity): CartItem
public function updateItem(string $buyableType, int $buyableId, int $quantity): CartItem
{
if ($quantity <= 0) {
throw ValidationException::withMessages([
@@ -118,18 +120,19 @@ class Cart extends Model
]);
}
return DB::transaction(function () use ($productVariantId, $quantity): CartItem {
return DB::transaction(function () use ($buyableType, $buyableId, $quantity): CartItem {
/** @var CartItem $item */
$item = $this->items()
->where('producto_variante_id', $productVariantId)
->where('buyable_type', $buyableType)
->where('buyable_id', $buyableId)
->lockForUpdate()
->firstOrFail();
$variant = $this->resolveScopedVariant($productVariantId, true);
$buyable = $this->resolveScopedBuyable($buyableType, $buyableId, true);
$delta = $quantity - $item->cantidad;
if ($delta > 0 && $variant->stock_tecnico < $delta) {
$maxAvailable = $variant->stock_tecnico + $item->cantidad;
if ($delta > 0 && $buyable->stock_tecnico < $delta) {
$maxAvailable = $buyable->stock_tecnico + $item->cantidad;
throw ValidationException::withMessages([
'cantidad' => "El máximo que se puede agregar es {$maxAvailable}.",
]);
@@ -139,49 +142,57 @@ class Cart extends Model
$item->save();
if ($delta > 0) {
$variant->incrementReservedStock($delta);
$buyable->incrementReservedStock($delta);
}
if ($delta < 0) {
$variant->decrementReservedStock(abs($delta));
$buyable->decrementReservedStock(abs($delta));
}
return $item->fresh();
});
}
public function removeItem(int $productVariantId): void
public function removeItem(string $buyableType, int $buyableId): void
{
DB::transaction(function () use ($productVariantId): void {
DB::transaction(function () use ($buyableType, $buyableId): void {
/** @var CartItem $item */
$item = $this->items()
->where('producto_variante_id', $productVariantId)
->where('buyable_type', $buyableType)
->where('buyable_id', $buyableId)
->lockForUpdate()
->firstOrFail();
$variant = $this->resolveScopedVariant($productVariantId, true);
$variant->decrementReservedStock($item->cantidad);
$buyable = $this->resolveScopedBuyable($buyableType, $buyableId, true);
$buyable->decrementReservedStock($item->cantidad);
$item->delete();
});
}
protected function resolveScopedVariant(int $productVariantId, bool $lockForUpdate = false): ProductVariant
protected function resolveScopedBuyable(string $buyableType, int $buyableId, bool $lockForUpdate = false)
{
$query = ProductVariant::query()
->whereKey($productVariantId)
if ($buyableType === 'variant') {
$query = \App\Domains\Catalog\Models\ProductVariant::query()
->whereKey($buyableId)
->whereHas('product', fn ($query) => $query->where('tenant_codigo', $this->tenant_codigo));
} elseif ($buyableType === 'bundle') {
$query = \App\Domains\Bundle\Models\Bundle::query()
->whereKey($buyableId)
->where('tenant_codigo', $this->tenant_codigo);
} else {
throw new \InvalidArgumentException('Invalid buyable type');
}
if ($lockForUpdate) {
$query->lockForUpdate();
}
/** @var ProductVariant|null $variant */
$variant = $query->first();
$buyable = $query->first();
if ($variant === null) {
throw new NotFoundHttpException('Product variant not found for tenant.');
if ($buyable === null) {
throw new NotFoundHttpException('Buyable not found for tenant.');
}
return $variant;
return $buyable;
}
}

View File

@@ -17,7 +17,8 @@ class AddCartItemRequest extends FormRequest
public function rules(): array
{
return [
'product_variant_id' => ['required', 'integer'],
'buyable_type' => ['required', 'string', \Illuminate\Validation\Rule::in(['variant', 'bundle'])],
'buyable_id' => ['required', 'integer'],
'cantidad' => ['required', 'integer', 'min:1'],
];
}

View File

@@ -15,29 +15,15 @@ class CartItemResource extends JsonResource
*/
public function toArray(Request $request): array
{
$variant = $this->variant;
$product = $variant?->product;
/** @var \App\Domains\Shared\Contracts\Buyable|null $buyable */
$buyable = $this->buyable;
$attributesText = '';
if ($variant && $variant->relationLoaded('definitions')) {
$attributesText = $variant->definitions
->map(function ($definition) {
$attrName = $definition->productAttribute?->attribute?->nombre;
$value = $definition->value;
return $attrName ? "{$attrName}: {$value}" : $value;
})
->filter()
->implode(', ');
}
$productName = $product?->nombre;
if ($productName && $attributesText !== '') {
$productName .= " ({$attributesText})";
}
$productName = $buyable?->getName();
$precio = $buyable?->getPrice();
$imageUrl = null;
if ($variant && $variant->relationLoaded('attachments')) {
$firstAttachment = $variant->attachments->first();
if ($this->buyable_type === 'variant' && $buyable && $buyable->relationLoaded('attachments')) {
$firstAttachment = $buyable->attachments->first();
if ($firstAttachment) {
$imageUrl = $firstAttachment->getTemporaryUrl(1440);
}
@@ -46,10 +32,10 @@ class CartItemResource extends JsonResource
return [
'id' => $this->id,
'cantidad' => $this->cantidad,
'precio_unitario' => $this->formatMoney($product?->precio),
'product_id' => $product?->id,
'product_variant_id' => $this->producto_variante_id,
'product' => $product === null ? null : [
'precio_unitario' => $this->formatMoney($precio),
'buyable_type' => $this->buyable_type,
'buyable_id' => $this->buyable_id,
'product' => $buyable === null ? null : [
'nombre' => $productName,
'imagen' => $imageUrl,
],

View File

@@ -32,12 +32,12 @@ class CartService
/**
* @return array{cart: Cart, guest_token: ?string}
*/
public function addItem(Tenant $tenant, Request $request, int $productVariantId, int $quantity): array
public function addItem(Tenant $tenant, Request $request, string $buyableType, int $buyableId, int $quantity): array
{
$resolvedIdentity = $this->resolveIdentity($request, true);
$identity = $resolvedIdentity['identity'];
$cart = $this->findOrCreateCart($tenant, $identity);
$cart->addItem($productVariantId, $quantity);
$cart->addItem($buyableType, $buyableId, $quantity);
return [
'cart' => $this->loadCart($cart),
@@ -45,20 +45,20 @@ class CartService
];
}
public function updateItemQuantity(Tenant $tenant, Request $request, int $productVariantId, int $quantity): Cart
public function updateItemQuantity(Tenant $tenant, Request $request, string $buyableType, int $buyableId, int $quantity): Cart
{
$identity = $this->requireIdentity($request);
$cart = $this->findCartOrFail($tenant, $identity);
$cart->updateItem($productVariantId, $quantity);
$cart->updateItem($buyableType, $buyableId, $quantity);
return $this->loadCart($cart);
}
public function removeItem(Tenant $tenant, Request $request, int $productVariantId): Cart
public function removeItem(Tenant $tenant, Request $request, string $buyableType, int $buyableId): Cart
{
$identity = $this->requireIdentity($request);
$cart = $this->findCartOrFail($tenant, $identity);
$cart->removeItem($productVariantId);
$cart->removeItem($buyableType, $buyableId);
return $this->loadCart($cart);
}

View File

@@ -8,6 +8,6 @@ Route::prefix('tenants/{tenant:codigo}')
->group(function (): void {
Route::get('cart', [CartController::class, 'show']);
Route::post('cart/items', [CartController::class, 'addItem']);
Route::patch('cart/items/{productVariant}', [CartController::class, 'updateItemQuantity']);
Route::delete('cart/items/{productVariant}', [CartController::class, 'removeItem']);
Route::patch('cart/items/{buyableType}/{buyableId}', [CartController::class, 'updateItemQuantity']);
Route::delete('cart/items/{buyableType}/{buyableId}', [CartController::class, 'removeItem']);
});

View File

@@ -12,7 +12,7 @@ use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Casts\Attribute;
use App\Domains\Shared\Contracts\Stockable;
use App\Domains\Shared\Contracts\Buyable;
#[Fillable([
'producto_id',
@@ -24,7 +24,7 @@ use App\Domains\Shared\Contracts\Stockable;
'minimum_use_date',
'maximum_use_date',
])]
class ProductVariant extends Model implements Stockable
class ProductVariant extends Model implements Buyable
{
use HasFactory;
@@ -54,6 +54,28 @@ class ProductVariant extends Model implements Stockable
}
}
public function getPrice(): float
{
return (float) ($this->product->precio ?? 0.0);
}
public function getName(): string
{
$name = $this->product->nombre ?? 'Producto';
if ($this->relationLoaded('definitions') && $this->definitions->isNotEmpty()) {
$definitions = $this->definitions->map(function ($def) {
return $def->value ?? $def->productAttribute?->attribute?->nombre;
})->filter()->implode(', ');
if ($definitions !== '') {
$name .= " ({$definitions})";
}
}
return $name;
}
public function incrementRealStock(int $amount): void
{
if ($amount < 0) {

View File

@@ -17,26 +17,30 @@ class PurchaseItemResource extends JsonResource
*/
public function toArray(Request $request): array
{
$variant = $this->variant;
$product = $variant?->product;
/** @var \App\Domains\Shared\Contracts\Buyable|null $buyable */
$buyable = $this->buyable;
$quantity = (int) ($this->cantidad ?? 0);
$unitPrice = $this->resolveUnitPrice();
$lineTotal = $this->resolveLineTotal($unitPrice, $quantity);
$imageUrl = null;
$attributes = [];
if ($this->buyable_type === 'variant' && $buyable) {
$imageUrl = $this->resolveImageUrl($buyable);
$attributes = $this->resolveAttributes($buyable);
}
return [
'id' => $this->id,
'quantity' => $quantity,
'unit_price' => $this->formatMoney($unitPrice),
'line_total' => $this->formatMoney($lineTotal),
'product' => $product === null ? null : [
'id' => $product->id,
'nombre' => $product->nombre,
'slug' => $product->slug,
'imagen' => $this->resolveImageUrl(),
],
'variant' => $variant === null ? null : [
'id' => $variant->id,
'attributes' => $this->resolveAttributes(),
'buyable_type' => $this->buyable_type,
'buyable_id' => $this->buyable_id,
'item_details' => $buyable === null ? null : [
'nombre' => $buyable->getName(),
'imagen' => $imageUrl,
'attributes' => $attributes,
],
];
}
@@ -48,7 +52,7 @@ class PurchaseItemResource extends JsonResource
}
if ($this->resource instanceof CartItem) {
return (float) ($this->variant?->product?->precio ?? 0);
return (float) ($this->buyable?->getPrice() ?? 0);
}
return 0.0;
@@ -63,15 +67,13 @@ class PurchaseItemResource extends JsonResource
return $unitPrice * $quantity;
}
protected function resolveImageUrl(): ?string
protected function resolveImageUrl($buyable): ?string
{
$variant = $this->variant;
if ($variant === null || ! $variant->relationLoaded('attachments')) {
if (! $buyable->relationLoaded('attachments')) {
return null;
}
$attachment = $variant->attachments->first();
$attachment = $buyable->attachments->first();
if ($attachment === null) {
return null;
@@ -83,15 +85,13 @@ class PurchaseItemResource extends JsonResource
/**
* @return array<int, array{name: string, value: mixed}>
*/
protected function resolveAttributes(): array
protected function resolveAttributes($buyable): array
{
$variant = $this->variant;
if ($variant === null || ! $variant->relationLoaded('definitions')) {
if (! $buyable->relationLoaded('definitions')) {
return [];
}
return $variant->definitions
return $buyable->definitions
->map(function ($definition): array {
return [
'name' => (string) ($definition->productAttribute?->attribute?->nombre ?? ''),

View File

@@ -29,7 +29,7 @@ class CheckoutService
]);
}
$cartItems->load('variant.product');
$cartItems->load('buyable');
$cart->setRelation('items', $cartItems);
$totalAmount = $cart->getTotalAmount();
@@ -63,7 +63,7 @@ class CheckoutService
$purchase->save();
}
return $purchase->load(['items.variant.product', 'items.variant.definitions.productAttribute.attribute']);
return $purchase->load(['items.buyable']);
});
}
@@ -82,7 +82,7 @@ class CheckoutService
}
if (in_array($purchase->status, [Purchase::STATUS_PAID, Purchase::STATUS_CANCELLED, Purchase::STATUS_REJECTED], true)) {
return $purchase->load(['items.variant.product', 'items.variant.definitions.productAttribute.attribute']);
return $purchase->load(['items.buyable']);
}
$purchase->update([
@@ -90,7 +90,7 @@ class CheckoutService
'total' => $purchase->calculateCurrentTotalAmount(),
]);
return $purchase->load(['items.variant.product', 'items.variant.definitions.productAttribute.attribute']);
return $purchase->load(['items.buyable']);
});
}
@@ -118,42 +118,36 @@ class CheckoutService
return;
}
$cartItems->load('variant.product');
$variants = $this->resolveTenantVariants($purchase->tenant, $cartItems);
$purchaseItemsPayload = $this->buildPurchaseItemsPayload($cartItems, $variants);
$cartItems->load('buyable');
$this->verifyTenantBuyables($purchase->tenant, $cartItems);
$purchaseItemsPayload = $this->buildPurchaseItemsPayload($cartItems);
$purchase->items()->createMany($purchaseItemsPayload);
$this->completeCartConversion($cart, $cartItems, $variants);
$this->completeCartConversion($cart, $cartItems);
});
}
/**
* @return Collection<int, ProductVariant>
*/
protected function resolveTenantVariants(Tenant $tenant, Collection $cartItems): Collection
protected function verifyTenantBuyables(Tenant $tenant, Collection $cartItems): void
{
$variantIds = $cartItems
->pluck('producto_variante_id')
->map(static fn (mixed $id): int => (int) $id)
->unique()
->values();
/** @var Collection<int, ProductVariant> $variants */
$variants = ProductVariant::query()
->with('product')
->whereIn('id', $variantIds)
->whereHas('product', fn ($query) => $query->where('tenant_codigo', $tenant->codigo))
->lockForUpdate()
->get()
->keyBy('id');
if ($variants->count() !== $variantIds->count()) {
foreach ($cartItems as $item) {
$buyable = $item->buyable;
if ($buyable === null) {
throw ValidationException::withMessages([
'cart_id' => 'One or more product variants do not belong to the tenant.',
'cart_id' => 'One or more buyables could not be loaded.',
]);
}
return $variants;
// Check tenant relation depending on type
if ($item->buyable_type === 'variant' && $buyable->product->tenant_codigo !== $tenant->codigo) {
throw ValidationException::withMessages([
'cart_id' => 'One or more product variants do not belong to the tenant.',
]);
} elseif ($item->buyable_type === 'bundle' && $buyable->tenant_codigo !== $tenant->codigo) {
throw ValidationException::withMessages([
'cart_id' => 'One or more bundles do not belong to the tenant.',
]);
}
}
}
/**
@@ -182,20 +176,19 @@ class CheckoutService
/**
* @param Collection<int, CartItem> $cartItems
* @param Collection<int, ProductVariant> $variants
* @return array<int, array<string, mixed>>
*/
protected function buildPurchaseItemsPayload(Collection $cartItems, Collection $variants): array
protected function buildPurchaseItemsPayload(Collection $cartItems): array
{
return $cartItems
->map(function (CartItem $item) use ($variants): array {
/** @var ProductVariant $variant */
$variant = $variants->get((int) $item['producto_variante_id']);
->map(function (CartItem $item): array {
$buyable = $item->buyable;
$quantity = (int) $item['cantidad'];
$unitPrice = (float) ($variant->product?->precio ?? 0);
$unitPrice = $buyable?->getPrice() ?? 0;
return [
'producto_variante_id' => $variant->getKey(),
'buyable_type' => $item->buyable_type,
'buyable_id' => $item->buyable_id,
'cantidad' => $quantity,
'precio_unitario' => $unitPrice,
'discount_total' => null,
@@ -208,17 +201,15 @@ class CheckoutService
/**
* @param Collection<int, CartItem> $cartItems
* @param Collection<int, ProductVariant> $variants
*/
protected function completeCartConversion(Cart $cart, Collection $cartItems, Collection $variants): void
protected function completeCartConversion(Cart $cart, Collection $cartItems): void
{
foreach ($cartItems as $item) {
/** @var ProductVariant $variant */
$variant = $variants->get((int) $item->producto_variante_id);
$buyable = $item->buyable;
$quantity = (int) $item->cantidad;
try {
$variant->confirmReservedStock($quantity);
$buyable->confirmReservedStock($quantity);
} catch (\InvalidArgumentException $exception) {
throw ValidationException::withMessages([
'cart_id' => 'The selected cart has inconsistent stock state.',

View File

@@ -2,8 +2,11 @@
namespace App\Domains\Shared\Contracts;
interface Stockable
interface Buyable
{
public function getPrice(): float;
public function getName(): string;
public function incrementRealStock(int $amount): void;
public function decrementRealStock(int $amount): void;