CRM/backend/app/Http/Resources/TaskResource.php

73 خطوط
3.0 KiB
PHP

<?php
namespace App\Http\Resources;
use App\Support\EntityResolver;
use Illuminate\Http\Request;
use Illuminate\Http\Resources\Json\JsonResource;
use Illuminate\Http\Resources\MissingValue;
use Illuminate\Support\Facades\Gate;
class TaskResource extends JsonResource
{
public static $wrap = null;
public function toArray(Request $request): array
{
$entity = $this->whenLoaded('taskable');
$taskable = $entity && ! $entity instanceof MissingValue
? [
'type' => EntityResolver::typeOf($entity),
'id' => $entity->getKey(),
'label' => $this->entityLabel($entity),
]
: null;
$gate = Gate::forUser($request->user());
return [
'id' => $this->id,
'subject' => $this->subject,
'description' => $this->description,
'taskable_type' => $taskable['type'] ?? null,
'taskable_id' => $taskable['id'] ?? $this->taskable_id,
'taskable' => $taskable,
'assigned_to' => $this->assigned_to,
'assignee' => $this->whenLoaded('assignee', fn () => $this->assignee?->only(['id', 'name', 'avatar', 'avatar_url'])),
'assigned_by' => $this->assigned_by,
'assigner' => $this->whenLoaded('assigner', fn () => $this->assigner?->only(['id', 'name'])),
'created_by' => $this->created_by,
'creator' => $this->whenLoaded('creator', fn () => $this->creator?->only(['id', 'name'])),
'priority' => $this->priority->value,
'status' => $this->status->value,
'due_at' => $this->due_at?->toISOString(),
'started_at' => $this->started_at?->toISOString(),
'completed_at' => $this->completed_at?->toISOString(),
'reminder_at' => $this->reminder_at?->toISOString(),
'parent_task_id' => $this->parent_task_id,
'parent' => $this->whenLoaded('parent', fn () => $this->parent?->only(['id', 'subject'])),
'estimated_minutes' => $this->estimated_minutes,
'visibility' => $this->visibility->value,
'version' => $this->version,
'is_overdue' => $this->is_overdue,
'capabilities' => [
'update' => $gate->allows('update', $this->resource),
'assign' => $gate->allows('assign', [$this->resource, $this->assigned_to]),
'transition' => $gate->allows('transition', $this->resource),
'delete' => $gate->allows('delete', $this->resource),
],
'created_at' => $this->created_at?->toISOString(),
'updated_at' => $this->updated_at?->toISOString(),
];
}
private function entityLabel(object $entity): string
{
return (string) ($entity->name
?? $entity->title
?? $entity->company
?? trim(($entity->first_name ?? '').' '.($entity->last_name ?? ''))
?: class_basename($entity).' #'.$entity->getKey());
}
}