83 lines
2.8 KiB
PHP
83 lines
2.8 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;
|
|
use Illuminate\Support\Collection;
|
|
|
|
/**
|
|
* @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' => $this->variantValues($variant),
|
|
])
|
|
->values(),
|
|
],
|
|
];
|
|
}
|
|
|
|
/** @return Collection<string, string|array<int, string>> */
|
|
private function variantValues(Variant $variant): Collection
|
|
{
|
|
$values = $variant->selectionValues();
|
|
$eventDates = $variant->selectedEventDates();
|
|
|
|
if ($eventDates->isNotEmpty()) {
|
|
$labels = $eventDates
|
|
->map(fn ($eventDate): string => $eventDate->date->format('d/m/Y').' · '
|
|
.substr($eventDate->time_start, 0, 5).' a '
|
|
.substr($eventDate->time_end, 0, 5))
|
|
->values();
|
|
|
|
$values->put(
|
|
'event_date',
|
|
$labels->count() === 1 ? $labels->first() : $labels->all(),
|
|
);
|
|
}
|
|
|
|
return $values;
|
|
}
|
|
|
|
protected function formatMoney(float|int|string|null $amount): string
|
|
{
|
|
return number_format((float) ($amount ?? 0), 2, '.', '');
|
|
}
|
|
}
|