ServicePackageResource.php 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051
  1. <?php
  2. namespace App\Http\Resources;
  3. use App\Models\ServicePackage;
  4. use Illuminate\Http\Request;
  5. use Illuminate\Http\Resources\Json\JsonResource;
  6. use Illuminate\Http\Resources\Json\AnonymousResourceCollection;
  7. class ServicePackageResource extends JsonResource
  8. {
  9. /**
  10. * Transform the resource into an array.
  11. *
  12. * @return array<string, mixed>
  13. */
  14. public function toArray(Request $request): array
  15. {
  16. return [
  17. 'id' => $this->id,
  18. 'client_id' => $this->client_id,
  19. 'provider_id' => $this->provider_id,
  20. 'provider' => $this->whenLoaded('provider', fn () => new ProviderResource($this->provider)),
  21. 'status' => $this->status?->value,
  22. 'schedule_ids' => $this->whenLoaded('items', fn () => $this->items->pluck('schedule_id')->values()),
  23. 'items' => $this->whenLoaded('items', fn () => ServicePackageItemResource::collection($this->items)),
  24. 'schedules' => $this->whenLoaded('items', fn () => ScheduleResource::collection(
  25. $this->items->pluck('schedule')->filter()->values(),
  26. )),
  27. 'total_amount' => $this->whenLoaded('items', fn () =>
  28. (float) $this->items
  29. ->filter(fn($item) => $item->schedule && ! in_array($item->schedule->status, ['cancelled', 'rejected'], true))
  30. ->sum(fn($item) => (float) $item->schedule->total_amount)
  31. ),
  32. 'created_at' => $this->created_at?->toISOString(),
  33. 'updated_at' => $this->updated_at?->toISOString(),
  34. ];
  35. }
  36. /**
  37. * @param \Illuminate\Database\Eloquent\Collection<ServicePackage> $resource
  38. * @return \Illuminate\Http\Resources\Json\AnonymousResourceCollection<ServicePackageResource>
  39. */
  40. public static function collection($resource): AnonymousResourceCollection
  41. {
  42. return parent::collection($resource);
  43. }
  44. }