Files
shopit-back/app/Domains/Sale/Resources/AdminApp/SaleDetailResource.php

88 lines
2.9 KiB
PHP

<?php
namespace App\Domains\Sale\Resources\AdminApp;
use App\Domains\Cart\Models\CartItem;
use App\Domains\Purchase\Models\Purchase;
use App\Domains\Purchase\Models\PurchaseItem;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Support\Collection;
/** @mixin Purchase */
class SaleDetailResource extends JsonResource
{
/** @return array<string, mixed> */
public function toArray(Request $request): array
{
$items = $this->saleItems();
return [
'id' => $this->id,
'items' => $items->map(fn (PurchaseItem|CartItem $item): array => [
'id' => $item->id,
'product' => $item instanceof PurchaseItem
? $item->item_nombre
: $item->selectedItem()?->getName(),
'event_dates' => $this->eventDates($item),
'quantity' => (int) $item->cantidad,
'unit_price' => $this->formatMoney($this->unitPrice($item)),
'total' => $this->formatMoney($this->lineTotal($item)),
])->values(),
'total' => $this->formatMoney($this->total),
];
}
/** @return Collection<int, PurchaseItem|CartItem> */
private function saleItems(): Collection
{
if ($this->items->isNotEmpty()) {
return $this->items;
}
return $this->cart?->items ?? collect();
}
/** @return list<string> */
private function eventDates(PurchaseItem|CartItem $item): array
{
if ($item instanceof CartItem) {
return $item->variant?->selectedEventDates()
->map(fn ($eventDate): string => $eventDate->date->format('Y-m-d'))
->values()
->all() ?? [];
}
return collect($item->variant_attributes ?? [])
->filter(fn (mixed $attribute): bool => is_array($attribute)
&& mb_strtolower(trim((string) ($attribute['name'] ?? ''))) === 'fecha')
->flatMap(function (array $attribute): array {
$value = $attribute['value'] ?? [];
return is_array($value) ? $value : [$value];
})
->filter(fn (mixed $date): bool => is_string($date) && $date !== '')
->values()
->all();
}
private function unitPrice(PurchaseItem|CartItem $item): float|int|string|null
{
return $item instanceof PurchaseItem
? $item->precio_unitario
: $item->selectedItem()?->getPrice();
}
private function lineTotal(PurchaseItem|CartItem $item): float|int|string|null
{
return $item instanceof PurchaseItem
? $item->total
: ($item->selectedItem()?->getPrice() ?? 0) * $item->cantidad;
}
private function formatMoney(float|int|string|null $amount): string
{
return number_format((float) ($amount ?? 0), 2, '.', '');
}
}