Files

143 lines
3.6 KiB
PHP
Raw Permalink Normal View History

<?php
namespace App\Livewire\TaskComments;
use App\Models\Task;
use App\Models\TaskComment;
use Livewire\Attributes\Layout;
use Livewire\Component;
#[Layout('components.layouts.app')]
class Index extends Component
{
public ?int $taskId = null;
public bool $showForm = false;
public ?int $editingId = null;
public string $body = '';
public string $authorType = 'user';
public string $authorName = '';
public function mount()
{
// Get task_id from query parameters
if (request()->has('task_id')) {
$this->taskId = (int) request('task_id');
}
// Set default author name for user
if (auth()->check()) {
$this->authorName = auth()->user()->name ?? 'User';
} else {
$this->authorName = 'User';
}
}
public function render()
{
$task = null;
$comments = collect();
if ($this->taskId) {
$task = Task::with(['project', 'comments'])->find($this->taskId);
$comments = $task ? $task->comments()->orderBy('created_at')->get() : collect();
}
return view('livewire.task-comments.index', [
'task' => $task,
'comments' => $comments,
'authorTypes' => TaskComment::AUTHOR_TYPES,
]);
}
public function create(): void
{
$this->resetForm();
$this->showForm = true;
}
public function edit(int $id): void
{
$comment = TaskComment::findOrFail($id);
$this->editingId = $comment->id;
$this->body = $comment->body;
$this->authorType = $comment->author_type;
$this->authorName = $comment->author_name;
$this->showForm = true;
}
public function save(): void
{
if (!$this->taskId) {
$this->addError('taskId', 'Task ID is required');
return;
}
$validated = $this->validate([
'body' => ['required', 'string'],
'authorType' => ['required', 'string', 'in:' . implode(',', TaskComment::AUTHOR_TYPES)],
'authorName' => ['required', 'string', 'max:255'],
]);
TaskComment::updateOrCreate(['id' => $this->editingId], [
'task_id' => $this->taskId,
'body' => $validated['body'],
'author_type' => $validated['authorType'],
'author_name' => $validated['authorName'],
]);
$this->resetForm();
$this->showForm = false;
}
public function delete(int $id): void
{
TaskComment::findOrFail($id)->delete();
}
public function resetForm(): void
{
$this->editingId = null;
$this->body = '';
$this->authorType = 'user';
// Keep the author name as it was
$this->resetValidation();
}
public function getAuthorColor(string $authorType): string
{
return match ($authorType) {
'ai' => 'bg-purple-100 text-purple-800',
'system' => 'bg-gray-100 text-gray-800',
'user' => 'bg-blue-100 text-blue-800',
default => 'bg-gray-100 text-gray-800',
};
}
public function setAuthorAsAI(): void
{
$this->authorType = 'ai';
$this->authorName = 'AI Assistant';
}
public function setAuthorAsUser(): void
{
$this->authorType = 'user';
if (auth()->check()) {
$this->authorName = auth()->user()->name ?? 'User';
} else {
$this->authorName = 'User';
}
}
public function setAuthorAsSystem(): void
{
$this->authorType = 'system';
$this->authorName = 'System';
}
}