58 lines
1.7 KiB
PHP
58 lines
1.7 KiB
PHP
<?php
|
|
|
|
namespace App\Domains\Purchase\Resources;
|
|
|
|
use Illuminate\Http\Request;
|
|
use Illuminate\Http\Resources\Json\JsonResource;
|
|
|
|
/**
|
|
* @mixin \App\Domains\Purchase\Models\Purchase
|
|
*/
|
|
class PurchaseResource extends JsonResource
|
|
{
|
|
/**
|
|
* @return array<string, mixed>
|
|
*/
|
|
public function toArray(Request $request): array
|
|
{
|
|
$items = $this->resource->relationLoaded('items')
|
|
? $this->resource->getRelation('items')
|
|
: collect();
|
|
|
|
$subtotal = $items->isNotEmpty()
|
|
? $items->reduce(
|
|
fn (float $carry, $item): float => $carry + ((float) $item->precio_unitario * $item->cantidad),
|
|
0.0,
|
|
)
|
|
: (float) ($this->total ?? 0);
|
|
|
|
$total = $items->isNotEmpty()
|
|
? $items->reduce(
|
|
fn (float $carry, $item): float => $carry + (float) $item->total,
|
|
0.0,
|
|
)
|
|
: (float) ($this->total ?? 0);
|
|
|
|
return [
|
|
'id' => $this->id,
|
|
'cart_id' => $this->cart_id,
|
|
'tenant_codigo' => $this->tenant_codigo,
|
|
'user_id' => $this->user_id,
|
|
'status' => $this->status,
|
|
'payment_method' => $this->payment_method,
|
|
'dni' => $this->dni,
|
|
'telefono' => $this->telefono,
|
|
'nombre_apellido' => $this->nombre_apellido,
|
|
'email' => $this->email,
|
|
'items' => PurchaseItemResource::collection($items),
|
|
'subtotal' => $this->formatMoney($subtotal),
|
|
'total' => $this->formatMoney($total),
|
|
];
|
|
}
|
|
|
|
protected function formatMoney(float|int|string|null $amount): string
|
|
{
|
|
return number_format((float) ($amount ?? 0), 2, '.', '');
|
|
}
|
|
}
|