*/ public function toArray(Request $request): array { $variant = $this->variant; $product = $variant?->product; $quantity = (int) ($this->cantidad ?? 0); $unitPrice = $this->resolveUnitPrice(); $lineTotal = $this->resolveLineTotal($unitPrice, $quantity); 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(), ], ]; } protected function resolveUnitPrice(): float { if ($this->resource instanceof PurchaseItem) { return (float) ($this->precio_unitario ?? 0); } if ($this->resource instanceof CartItem) { return (float) ($this->variant?->product?->precio ?? 0); } return 0.0; } protected function resolveLineTotal(float $unitPrice, int $quantity): float { if ($this->resource instanceof PurchaseItem) { return (float) ($this->total ?? 0); } return $unitPrice * $quantity; } protected function resolveImageUrl(): ?string { $variant = $this->variant; if ($variant === null || ! $variant->relationLoaded('attachments')) { return null; } $attachment = $variant->attachments->first(); if ($attachment === null) { return null; } return $attachment->getTemporaryUrl(1440); } /** * @return array */ protected function resolveAttributes(): array { $variant = $this->variant; if ($variant === null || ! $variant->relationLoaded('definitions')) { return []; } return $variant->definitions ->map(function ($definition): array { return [ 'name' => (string) ($definition->productAttribute?->attribute?->nombre ?? ''), 'value' => $definition->value, ]; }) ->filter(fn (array $attribute): bool => $attribute['name'] !== '' || $attribute['value'] !== null) ->values() ->all(); } protected function formatMoney(float|int|string|null $amount): ?string { if ($amount === null) { return null; } return number_format((float) $amount, 2, '.', ''); } }