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 ceb1e2b04a
commit 480ee70393
12 changed files with 230 additions and 203 deletions

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

@@ -4,6 +4,7 @@ namespace App\Domains\Purchase\Services;
use App\Domains\Cart\Models\Cart;
use App\Domains\Cart\Models\CartItem;
use App\Domains\Bundle\Models\Bundle;
use App\Domains\Catalog\Models\ProductVariant;
use App\Domains\Purchase\Models\Purchase;
use App\Domains\Tenant\Models\Tenant;
@@ -29,7 +30,7 @@ class CheckoutService
]);
}
$cartItems->load('variant.product');
$cartItems->load('buyable');
$cart->setRelation('items', $cartItems);
$totalAmount = $cart->getTotalAmount();
@@ -63,7 +64,7 @@ class CheckoutService
$purchase->save();
}
return $purchase->load(['items.variant.product', 'items.variant.definitions.productAttribute.attribute']);
return $purchase->load(['items.buyable']);
});
}
@@ -82,7 +83,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 +91,7 @@ class CheckoutService
'total' => $purchase->calculateCurrentTotalAmount(),
]);
return $purchase->load(['items.variant.product', 'items.variant.definitions.productAttribute.attribute']);
return $purchase->load(['items.buyable']);
});
}
@@ -123,42 +124,37 @@ class CheckoutService
]);
}
$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();
foreach ($cartItems as $item) {
$buyable = $item->buyable;
if ($buyable === null) {
throw ValidationException::withMessages([
'cart_id' => 'One or more buyables could not be loaded.',
]);
}
/** @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 ($item->buyable_type === ProductVariant::class && $buyable->product->tenant_codigo !== $tenant->codigo) {
throw ValidationException::withMessages([
'cart_id' => 'One or more product variants do not belong to the tenant.',
]);
}
if ($variants->count() !== $variantIds->count()) {
throw ValidationException::withMessages([
'cart_id' => 'One or more product variants do not belong to the tenant.',
]);
if ($item->buyable_type === Bundle::class && $buyable->tenant_codigo !== $tenant->codigo) {
throw ValidationException::withMessages([
'cart_id' => 'One or more bundles do not belong to the tenant.',
]);
}
}
return $variants;
}
/**
@@ -187,20 +183,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,
@@ -213,17 +208,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->buy($quantity);
$buyable->buy($quantity);
} catch (\InvalidArgumentException $exception) {
throw ValidationException::withMessages([
'cart_id' => 'The selected cart has inconsistent stock state.',