60 lines
2.0 KiB
PHP
60 lines
2.0 KiB
PHP
<?php
|
|
|
|
namespace App\Domains\Cart\Resources;
|
|
|
|
use App\Domains\Cart\Models\CartItem;
|
|
use App\Domains\Catalog\Enums\InventoryPolicy;
|
|
use App\Domains\Catalog\Models\Variant;
|
|
use Illuminate\Http\Request;
|
|
use Illuminate\Http\Resources\Json\JsonResource;
|
|
|
|
/**
|
|
* @mixin CartItem
|
|
*/
|
|
class CartItemResource extends JsonResource
|
|
{
|
|
/**
|
|
* @return array<string, mixed>
|
|
*/
|
|
public function toArray(Request $request): array
|
|
{
|
|
$selectedItem = $this->selectedItem();
|
|
$imageUrl = null;
|
|
|
|
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($selectedItem?->getPrice()),
|
|
'catalog_item_id' => $this->catalog_item_id,
|
|
'variant_id' => $this->variant_id,
|
|
'product' => $selectedItem === null ? null : [
|
|
'nombre' => $selectedItem->getName(),
|
|
'imagen' => $imageUrl,
|
|
'variants' => $this->catalogItem->variants
|
|
->map(fn (Variant $variant): array => [
|
|
'id' => $variant->id,
|
|
'precio' => $this->formatMoney($variant->getPrice()),
|
|
'stock_tecnico' => $this->catalogItem->inventory_policy === InventoryPolicy::Unlimited
|
|
? null
|
|
: $variant->inventory->availableStock(),
|
|
'values' => $variant->selectionOptions($this->catalogItem->itemAttributes),
|
|
])
|
|
->values(),
|
|
],
|
|
];
|
|
}
|
|
|
|
protected function formatMoney(float|int|string|null $amount): string
|
|
{
|
|
return number_format((float) ($amount ?? 0), 2, '.', '');
|
|
}
|
|
}
|