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 ?? ''),