feat(tasks): complete task management system with Kanban, Calendar, notifications

- Add Task model with subtasks, priorities, status transitions, dates, hours
- Add Comment polymorphic model for tasks/issues/projects
- Livewire components: TaskManager (list+filters), TaskForm (modal), TaskDetail, TaskKanban (drag&drop), TaskCalendar (FullCalendar)
- TaskPolicy with permissions (view/create/edit/delete/assign/manage all)
- Notifications: assigned, status change, overdue, comment added
- Daily overdue notification job scheduled
- Dashboard widget unifies IssueTask + Task
- i18n: en/es/fr/ru (393 keys each)
- Routes, navigation, offline sync support
- 101 tests passing, Pint compliant on new files
This commit is contained in:
Javier Braña
2026-08-03 13:44:10 +02:00
parent a65d4b12f2
commit ba614bddbc
62 changed files with 5878 additions and 382 deletions
+22 -4
View File
@@ -2,11 +2,11 @@
namespace App\Http\Controllers;
use App\Models\Feature;
use App\Models\Inspection;
use App\Models\PendingSync;
use App\Models\Phase;
use App\Models\Inspection;
use App\Models\Feature;
use App\Models\Media;
use App\Models\Task;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Storage;
@@ -16,7 +16,7 @@ class OfflineSyncController extends Controller
public function storePending(Request $request)
{
$payload = $request->validate([
'action' => 'required|in:progress_update,inspection,feature_create,media_upload,task_complete',
'action' => 'required|in:progress_update,inspection,feature_create,media_upload,task_complete,task_create,task_update',
'payload' => 'required|array',
]);
$pending = PendingSync::create([
@@ -24,6 +24,7 @@ class OfflineSyncController extends Controller
'action' => $payload['action'],
'payload' => $payload['payload'],
]);
return response()->json(['queued' => true]);
}
@@ -89,6 +90,22 @@ class OfflineSyncController extends Controller
// For now, just log and mark as success
\Log::info('Task completed offline', $pending->payload);
$result['success'] = true;
} elseif ($pending->action === 'task_create') {
$task = Task::create($pending->payload);
$result['success'] = true;
$result['data'] = ['task_id' => $task->id, 'uuid' => $task->uuid];
} elseif ($pending->action === 'task_update') {
$task = Task::find($pending->payload['id'] ?? null);
if ($task) {
// Remove fields that shouldn't be mass updated
$data = $pending->payload;
unset($data['id'], $data['uuid'], $data['created_at'], $data['updated_at'], $data['deleted_at']);
$task->update($data);
$result['success'] = true;
$result['data'] = ['task_id' => $task->id];
} else {
$result['error'] = 'Task not found';
}
} else {
$result['error'] = 'Unknown action type';
}
@@ -103,6 +120,7 @@ class OfflineSyncController extends Controller
$results[] = $result;
}
return response()->json(['synced' => $results]);
}
}
+5 -4
View File
@@ -16,11 +16,12 @@ class SetLocale
public function handle(Request $request, Closure $next)
{
$locale = null;
$allowedLocales = ['en', 'es', 'fr', 'ru'];
// 1. From authenticated user preference
if (Auth::check()) {
$userLocale = Auth::user()->locale;
if ($userLocale && in_array($userLocale, ['en', 'es'])) {
if ($userLocale && in_array($userLocale, $allowedLocales)) {
$locale = $userLocale;
}
}
@@ -28,7 +29,7 @@ class SetLocale
// 2. From session
if (!$locale && Session::has('locale')) {
$sessionLocale = Session::get('locale');
if (in_array($sessionLocale, ['en', 'es'])) {
if (in_array($sessionLocale, $allowedLocales)) {
$locale = $sessionLocale;
}
}
@@ -36,14 +37,14 @@ class SetLocale
// 3. From browser Accept-Language
if (!$locale) {
$browserLang = substr($request->server('HTTP_ACCEPT_LANGUAGE', 'en'), 0, 2);
if (in_array($browserLang, ['en', 'es'])) {
if (in_array($browserLang, $allowedLocales)) {
$locale = $browserLang;
}
}
// 4. Default to app locale
if (!$locale) {
$locale = config('app.locale', 'es');
$locale = config('app.locale', 'en');
}
App::setLocale($locale);
+35
View File
@@ -0,0 +1,35 @@
<?php
namespace App\Jobs;
use App\Models\Task;
use App\Notifications\TaskOverdueNotification;
use Illuminate\Bus\Queueable;
use Illuminate\Contracts\Queue\ShouldQueue;
use Illuminate\Foundation\Bus\Dispatchable;
use Illuminate\Queue\InteractsWithQueue;
use Illuminate\Queue\SerializesModels;
class NotifyOverdueTasks implements ShouldQueue
{
use Dispatchable, InteractsWithQueue, Queueable, SerializesModels;
public function handle(): void
{
$overdueTasks = Task::overdue()
->with(['assignee', 'project'])
->get();
foreach ($overdueTasks as $task) {
// Notify assignee
if ($task->assignee) {
$task->assignee->notify(new TaskOverdueNotification($task));
}
// Notify creator (if different from assignee)
if ($task->creator && $task->creator->id !== $task->assignee?->id) {
$task->creator->notify(new TaskOverdueNotification($task));
}
}
}
}
+15 -4
View File
@@ -11,14 +11,22 @@ class LanguageSwitcher extends Component
{
public string $currentLocale;
/** Idiomas disponibles con nombre y bandera. */
public array $languages = [
'en' => ['name' => 'English', 'flag' => 'gb.svg'],
'es' => ['name' => 'Español', 'flag' => 'es.svg'],
'fr' => ['name' => 'Français', 'flag' => 'fr.svg'],
'ru' => ['name' => 'Русский', 'flag' => 'ru.svg'],
];
public function mount(): void
{
$this->currentLocale = App::getLocale();
}
public function switchLanguage(string $locale): void
public function updatedCurrentLocale(string $locale): void
{
if (!in_array($locale, ['en', 'es'])) {
if (!in_array($locale, ['en', 'es', 'fr', 'ru'])) {
return;
}
@@ -31,11 +39,14 @@ class LanguageSwitcher extends Component
}
// Dispatch a browser event — JavaScript reloads the page.
// PHP-side redirects break because $this->redirect() runs inside
// /livewire/update (the AJAX endpoint), not on the real page URL.
$this->dispatch('locale-changed');
}
public function switchLanguage(string $locale): void
{
$this->updatedCurrentLocale($locale);
}
public function render()
{
return view('livewire.common.language-switcher');
+21 -14
View File
@@ -83,20 +83,27 @@ class InspectionTable extends DataTableComponent
->html(),
Column::make('Acciones')
->label(fn ($row) =>
'<div class="flex justify-end gap-1">
<button wire:click="$dispatch(\'map-view-inspection\', { id: ' . $row->id . ' })"
class="btn btn-xs btn-ghost" title="Ver inspección">
<svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"/></svg>
</button>
@can("edit inspections")
<button wire:click="$dispatch(\'edit-inspection\', { id: ' . $row->id . ' })"
class="btn btn-xs btn-ghost" title="Editar inspección">
<svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"/></svg>
</button>
@endcan
</div>')
->html(),
->label(fn ($row) =>
'<div class="flex justify-end gap-1">'
. '<button wire:click="$dispatch(\'map-view-inspection\', { id: ' . $row->id . ' })"'
. 'class="btn btn-xs btn-ghost" title="Ver inspección">'
. '<svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"/></svg>'
. '</button>'
. '@can("edit inspections")'
. '<button wire:click="$dispatch(\'edit-inspection\', { id: ' . $row->id . ' })"'
. 'class="btn btn-xs btn-ghost" title="Editar inspección">'
. '<svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"/></svg>'
. '</button>'
. '@endcan'
. '@can("delete inspections")'
. '<button wire:click="$dispatch(\'delete-inspection\', { id: ' . $row->id . ' })"'
. 'class="btn btn-xs btn-ghost btn-error" title="Eliminar inspección"'
. 'onclick="return confirm(\'¿Eliminar esta inspección? No se puede deshacer.\');">'
. '<svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/></svg>'
. '</button>'
. '@endcan'
. '</div>')
->html(),
];
}
+62
View File
@@ -6,6 +6,7 @@ use Livewire\Component;
use Livewire\Attributes\On;
use Livewire\WithFileUploads;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use App\Models\Project;
use App\Models\Phase;
use App\Models\Layer;
@@ -13,6 +14,7 @@ use App\Models\Feature;
use App\Models\Inspection;
use App\Models\InspectionTemplate;
use App\Models\Issue;
use App\Models\Media;
class ProjectMap extends Component
{
@@ -353,6 +355,14 @@ class ProjectMap extends Component
$this->dispatch('notify', 'Inspección guardada correctamente');
}
// Notificar a usuarios del proyecto (excepto creador)
$usersToNotify = $this->project->users()
->where('user_id', '!=', auth()->id())
->get();
foreach ($usersToNotify as $user) {
$user->notify(new \App\Notifications\InspectionCompletedNotification($inspection));
}
// Reload global list
$this->allInspections = Inspection::where('project_id', $this->project->id)
->with(['feature.layer.phase', 'template', 'user'])
@@ -547,6 +557,58 @@ class ProjectMap extends Component
$this->dispatch('notify', 'Inspección actualizada correctamente');
}
// ─── Delete Inspection ───────────────────────────────────────────────────────
#[On('delete-inspection')]
public function deleteInspection($id)
{
\Log::info('deleteInspection: START', ['id' => $id]);
if (!auth()->user()->can('delete inspections')) {
$this->dispatch('notify', 'Sin permisos para eliminar inspecciones.');
\Log::info('deleteInspection: permission denied');
return;
}
$ins = Inspection::where('project_id', $this->project->id)
->with(['feature', 'media'])
->find($id);
if (!$ins) {
\Log::info('deleteInspection: inspection not found', ['id' => $id]);
$this->dispatch('notify', 'Inspección no encontrada');
return;
}
\Log::info('deleteInspection: BEFORE delete', ['id' => $ins->id, 'deleted_at' => $ins->deleted_at, 'project_id' => $ins->project_id]);
// Delete associated media files (booted event deletes physical files)
$ins->media()->get()->each->delete();
$result = $ins->delete();
\Log::info('deleteInspection: delete() returned', ['result' => $result]);
$fresh = $ins->fresh();
\Log::info('deleteInspection: AFTER delete', ['id' => $id, 'fresh_deleted_at' => $fresh ? $fresh->deleted_at : 'null', 'fresh_exists' => $fresh ? 'yes' : 'no']);
// Refresh lists
$this->allInspections = Inspection::where('project_id', $this->project->id)
->with(['feature.layer.phase', 'template', 'user'])
->orderBy('created_at', 'desc')
->get();
$this->loadInspectionHistory();
$this->dispatch('notify', 'Inspección eliminada correctamente');
\Log::info('deleteInspection: dispatched notify SUCCESS');
// Notificar a usuarios del proyecto (excepto eliminador)
$usersToNotify = $this->project->users()
->where('user_id', '!=', auth()->id())
->get();
foreach ($usersToNotify as $user) {
$user->notify(new \App\Notifications\InspectionDeletedNotification($ins));
}
}
// ─── Feature images ──────────────────────────────────────────────────────────
public function toggleFeatureImages()
+167
View File
@@ -0,0 +1,167 @@
<?php
namespace App\Livewire\Tasks;
use App\Models\Project;
use App\Models\Task;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Livewire\Attributes\Layout;
use Livewire\Attributes\On;
use Livewire\Component;
#[Layout('layouts.app')]
class TaskCalendar extends Component
{
public ?Project $project = null;
public $viewMode = 'dayGridMonth'; // dayGridMonth, timeGridWeek, timeGridDay, listWeek
public $search = '';
public $assigneeFilter = '';
public $phaseFilter = '';
public $priorityFilter = '';
public $statusFilter = '';
protected $queryString = [
'viewMode' => ['except' => 'dayGridMonth'],
'search' => ['except' => ''],
'assigneeFilter' => ['except' => ''],
'phaseFilter' => ['except' => ''],
'priorityFilter' => ['except' => ''],
'statusFilter' => ['except' => ''],
];
public function mount(?Project $project = null): void
{
$this->project = $project;
if ($project) {
abort_unless($this->canAccessProject() && Auth::user()->can('view tasks'), 403);
} else {
abort_unless(Auth::user()->can('view tasks'), 403);
}
}
private function canAccessProject(): bool
{
$user = Auth::user();
return $user->can('manage all')
|| ($this->project && $this->project->users()->where('user_id', $user->id)->exists());
}
#[On('tasksChanged')]
public function refreshCalendar(): void
{
// Trigger re-render
}
public function render()
{
$user = Auth::user();
$query = Task::with(['project', 'phase', 'assignee'])
->where(function ($q) use ($user) {
if (! $user->can('manage all tasks')) {
$q->whereHas('project', function ($sub) use ($user) {
$sub->whereHas('users', function ($sub2) use ($user) {
$sub2->where('user_id', $user->id);
});
});
}
});
if ($this->project) {
$query->where('project_id', $this->project->id);
}
if ($this->search) {
$query->where(function ($q) {
$q->where('title', 'like', '%'.$this->search.'%')
->orWhere('description', 'like', '%'.$this->search.'%');
});
}
if ($this->assigneeFilter) {
$query->where('assigned_to', $this->assigneeFilter);
}
if ($this->phaseFilter) {
$query->where('phase_id', $this->phaseFilter);
}
if ($this->priorityFilter) {
$query->where('priority', $this->priorityFilter);
}
if ($this->statusFilter) {
$query->where('status', $this->statusFilter);
}
$tasks = $query->get();
// Transform tasks to FullCalendar events
$events = $tasks->map(function ($task) {
$start = $task->start_date ?? $task->due_date ?? $task->created_at->toDateString();
$end = $task->due_date ?? $task->start_date;
return [
'id' => $task->id,
'title' => $task->title,
'start' => $start,
'end' => $end ? $end->addDay()->toDateString() : null, // FullCalendar end is exclusive
'url' => route('projects.tasks.show', [$task->project_id, $task->id]),
'backgroundColor' => $task->priority_color,
'borderColor' => $task->priority_color,
'textColor' => '#ffffff',
'extendedProps' => [
'status' => $task->status,
'statusLabel' => $task->status_label,
'priority' => $task->priority,
'priorityLabel' => $task->priority_label,
'project' => $task->project->name ?? '—',
'phase' => $task->phase->name ?? '—',
'assignee' => $task->assignee->name ?? 'Sin asignar',
'dueDate' => $task->due_date?->format('d/m/Y'),
'isOverdue' => $task->is_overdue,
'isDueToday' => $task->is_due_today,
'progress' => $task->progress,
'subtasksCount' => $task->subtasks->count(),
'completedSubtasksCount' => $task->subtasks->where('status', 'completed')->count(),
],
'classNames' => [
'fc-task-'.$task->status,
$task->is_overdue ? 'fc-task-overdue' : '',
$task->is_due_today ? 'fc-task-due-today' : '',
],
];
})->toArray();
// Filter options
$assignees = User::whereHas('assignedTasks', function ($q) use ($user) {
if (! $user->can('manage all tasks')) {
$q->whereHas('project', function ($sub) use ($user) {
$sub->whereHas('users', function ($sub2) use ($user) {
$sub2->where('user_id', $user->id);
});
});
}
})->get(['id', 'name']);
$phases = $this->project
? $this->project->phases()->get(['id', 'name'])
: collect();
return view('livewire.tasks.task-calendar', [
'events' => json_encode($events),
'assignees' => $assignees,
'phases' => $phases,
'statusOptions' => Task::statusOptions(),
'priorityOptions' => Task::priorityOptions(),
]);
}
}
+177
View File
@@ -0,0 +1,177 @@
<?php
namespace App\Livewire\Tasks;
use App\Models\Comment;
use App\Models\Project;
use App\Models\Task;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;
use Livewire\Attributes\Layout;
use Livewire\Component;
use Livewire\WithFileUploads;
#[Layout('layouts.app')]
class TaskDetail extends Component
{
use WithFileUploads;
public Task $task;
public ?Project $project = null;
// Comment form
public $commentBody = '';
public $editingCommentId = null;
public $editingCommentBody = '';
// Subtask form
public $subtaskTitle = '';
protected $listeners = ['tasksChanged' => '$refresh', 'commentAdded' => '$refresh', 'subtaskAdded' => '$refresh'];
public function mount(Task $task): void
{
$this->task = $task->load(['project', 'phase', 'assignee', 'creator', 'completer', 'subtasks', 'media', 'comments.user', 'comments.replies.user']);
$this->project = $this->task->project;
abort_unless(Auth::user()->can('view', $this->task), 403);
}
public function addComment(): void
{
$this->validate(['commentBody' => 'required|string|max:5000']);
$this->task->comments()->create([
'user_id' => Auth::id(),
'body' => $this->commentBody,
]);
$this->commentBody = '';
$this->dispatch('commentAdded');
$this->dispatch('tasksChanged');
}
public function startEditComment($commentId): void
{
$comment = $this->task->comments()->find($commentId);
if ($comment && $comment->user_id === Auth::id()) {
$this->editingCommentId = $commentId;
$this->editingCommentBody = $comment->body;
}
}
public function saveEditComment(): void
{
$this->validate(['editingCommentBody' => 'required|string|max:5000']);
$comment = Comment::find($this->editingCommentId);
if ($comment && $comment->user_id === Auth::id()) {
$comment->update(['body' => $this->editingCommentBody]);
}
$this->editingCommentId = null;
$this->editingCommentBody = '';
$this->dispatch('commentAdded');
}
public function cancelEditComment(): void
{
$this->editingCommentId = null;
$this->editingCommentBody = '';
}
public function deleteComment($commentId): void
{
$comment = Comment::find($commentId);
if ($comment && ($comment->user_id === Auth::id() || Auth::user()->can('manage all tasks'))) {
$comment->delete();
$this->dispatch('commentAdded');
}
}
public function addSubtask(): void
{
$this->validate(['subtaskTitle' => 'required|string|max:255']);
$maxOrder = $this->task->subtasks()->max('order') ?? 0;
$this->task->subtasks()->create([
'title' => $this->subtaskTitle,
'status' => 'pending',
'priority' => 'medium',
'project_id' => $this->task->project_id,
'phase_id' => $this->task->phase_id,
'parent_task_id' => $this->task->id,
'created_by' => Auth::id(),
'order' => $maxOrder + 1,
'uuid' => Str::uuid(),
]);
$this->subtaskTitle = '';
$this->dispatch('subtaskAdded');
$this->dispatch('tasksChanged');
}
public function updateSubtaskStatus(Task $subtask, string $status): void
{
abort_unless(Auth::user()->can('update', $subtask), 403);
$data = ['status' => $status];
if ($status === 'completed') {
$data['completed_at'] = now();
$data['completed_by'] = Auth::id();
} elseif ($subtask->status === 'completed') {
$data['completed_at'] = null;
$data['completed_by'] = null;
}
$subtask->update($data);
$this->dispatch('tasksChanged');
}
public function deleteSubtask(Task $subtask): void
{
abort_unless(Auth::user()->can('delete', $subtask), 403);
$subtask->delete();
$this->dispatch('tasksChanged');
}
public function changeStatus(string $status): void
{
abort_unless(Auth::user()->can('update', $this->task), 403);
$oldStatus = $this->task->status;
$data = ['status' => $status];
if ($oldStatus !== 'completed' && $status === 'completed') {
$data['completed_at'] = now();
$data['completed_by'] = Auth::id();
} elseif ($oldStatus === 'completed' && $status !== 'completed') {
$data['completed_at'] = null;
$data['completed_by'] = null;
}
$this->task->update($data);
$this->task->refresh();
$this->dispatch('tasksChanged');
}
public function render()
{
$assignees = User::whereHas('assignedTasks', function ($q) {
if ($this->project) {
$q->where('project_id', $this->project->id);
}
})->get(['id', 'name']);
return view('livewire.tasks.task-detail', [
'assignees' => $assignees,
'statusOptions' => Task::statusOptions(),
'priorityOptions' => Task::priorityOptions(),
]);
}
}
+206
View File
@@ -0,0 +1,206 @@
<?php
namespace App\Livewire\Tasks;
use App\Models\Project;
use App\Models\Task;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;
use Livewire\Attributes\Layout;
use Livewire\Attributes\Validate;
use Livewire\Component;
use Livewire\WithFileUploads;
#[Layout('layouts.app')]
class TaskForm extends Component
{
use WithFileUploads;
public ?Task $task = null;
public ?Project $project = null;
// Form fields
#[Validate('required|string|max:255')]
public $title = '';
#[Validate('nullable|string')]
public $description = '';
#[Validate('nullable|exists:phases,id')]
public $phase_id = '';
#[Validate('required|in:pending,in_progress,completed,cancelled')]
public $status = 'pending';
#[Validate('required|in:low,medium,high,critical')]
public $priority = 'medium';
#[Validate('nullable|exists:users,id')]
public $assigned_to = '';
#[Validate('nullable|date|after_or_equal:start_date')]
public $due_date = '';
#[Validate('nullable|date|before_or_equal:due_date')]
public $start_date = '';
#[Validate('nullable|integer|min:0|max:10000')]
public $estimated_hours = '';
#[Validate('nullable|integer|min:0|max:10000')]
public $actual_hours = '';
#[Validate('nullable|integer|min:0')]
public $order = 0;
// For subtasks
#[Validate('nullable|exists:tasks,id')]
public $parent_task_id = '';
// UI state
public $showModal = false;
public $mode = 'create'; // 'create' or 'edit'
protected $listeners = ['openTaskModal' => 'openModal'];
public function mount(?Project $project = null, ?Task $task = null): void
{
$this->project = $project;
$this->task = $task;
if ($task) {
$this->mode = 'edit';
$this->fillFromTask($task);
abort_unless(Auth::user()->can('update', $task), 403);
} else {
$this->mode = 'create';
abort_unless(Auth::user()->can('create tasks', $project), 403);
}
}
public function openModal(array $params = []): void
{
$this->resetForm();
$this->mode = $params['mode'] ?? 'create';
$this->project = $params['project'] ?? $this->project;
$this->task = $params['task'] ?? null;
if ($this->task) {
$this->fillFromTask($this->task);
} else {
$this->status = 'pending';
$this->priority = 'medium';
$this->order = 0;
}
$this->showModal = true;
}
private function fillFromTask(Task $task): void
{
$this->title = $task->title;
$this->description = $task->description;
$this->phase_id = $task->phase_id ?? '';
$this->status = $task->status;
$this->priority = $task->priority;
$this->assigned_to = $task->assigned_to ?? '';
$this->due_date = $task->due_date?->format('Y-m-d') ?? '';
$this->start_date = $task->start_date?->format('Y-m-d') ?? '';
$this->estimated_hours = $task->estimated_hours ?? '';
$this->actual_hours = $task->actual_hours ?? '';
$this->order = $task->order ?? 0;
$this->parent_task_id = $task->parent_task_id ?? '';
}
private function resetForm(): void
{
$this->reset(['title', 'description', 'phase_id', 'status', 'priority', 'assigned_to', 'due_date', 'start_date', 'estimated_hours', 'actual_hours', 'order', 'parent_task_id']);
$this->resetValidation();
}
public function save(): void
{
$validated = $this->validate();
$data = [
'title' => $validated['title'],
'description' => $validated['description'] ?? null,
'phase_id' => $validated['phase_id'] ?? null,
'status' => $validated['status'],
'priority' => $validated['priority'],
'assigned_to' => $validated['assigned_to'] ?? null,
'due_date' => $validated['due_date'] ?? null,
'start_date' => $validated['start_date'] ?? null,
'estimated_hours' => $validated['estimated_hours'] ?? null,
'actual_hours' => $validated['actual_hours'] ?? null,
'order' => $validated['order'],
'parent_task_id' => $validated['parent_task_id'] ?? null,
'project_id' => $this->project?->id,
'created_by' => Auth::id(),
];
// Handle status transitions
if ($this->mode === 'edit' && $this->task) {
$oldStatus = $this->task->status;
$newStatus = $data['status'];
if ($oldStatus !== 'completed' && $newStatus === 'completed') {
$data['completed_at'] = now();
$data['completed_by'] = Auth::id();
} elseif ($oldStatus === 'completed' && $newStatus !== 'completed') {
$data['completed_at'] = null;
$data['completed_by'] = null;
}
$this->task->update($data);
$task = $this->task;
session()->flash('message', 'Tarea actualizada correctamente');
} else {
$data['uuid'] = Str::uuid();
$task = Task::create($data);
session()->flash('message', 'Tarea creada correctamente');
}
$this->dispatch('tasksChanged');
$this->dispatch('taskSaved', taskId: $task->id);
$this->closeModal();
}
public function closeModal(): void
{
$this->showModal = false;
$this->resetForm();
$this->mode = 'create';
$this->task = null;
}
public function render()
{
$assignees = User::whereHas('assignedTasks', function ($q) {
if ($this->project) {
$q->where('project_id', $this->project->id);
}
})->get(['id', 'name']);
$phases = $this->project ? $this->project->phases->pluck('name', 'id') : collect();
// For parent task selector (only sibling tasks in same project)
$parentTasks = $this->project
? Task::where('project_id', $this->project->id)
->whereNull('parent_task_id')
->when($this->task, fn ($q) => $q->where('id', '!=', $this->task->id))
->get(['id', 'title'])
: collect();
return view('livewire.tasks.task-form', [
'assignees' => $assignees,
'phases' => $phases,
'parentTasks' => $parentTasks,
'statusOptions' => Task::statusOptions(),
'priorityOptions' => Task::priorityOptions(),
]);
}
}
+194
View File
@@ -0,0 +1,194 @@
<?php
namespace App\Livewire\Tasks;
use App\Models\Project;
use App\Models\Task;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Livewire\Attributes\Layout;
use Livewire\Attributes\On;
use Livewire\Component;
use Livewire\WithPagination;
#[Layout('layouts.app')]
class TaskKanban extends Component
{
use WithPagination;
public ?Project $project = null;
public $search = '';
public $assigneeFilter = '';
public $phaseFilter = '';
public $priorityFilter = '';
public $showOverdueOnly = false;
public $perPage = 50;
protected $queryString = [
'search' => ['except' => ''],
'assigneeFilter' => ['except' => ''],
'phaseFilter' => ['except' => ''],
'priorityFilter' => ['except' => ''],
'showOverdueOnly' => ['except' => false],
];
public function mount(?Project $project = null): void
{
$this->project = $project;
if ($project) {
abort_unless($this->canAccessProject() && Auth::user()->can('view tasks'), 403);
} else {
abort_unless(Auth::user()->can('view tasks'), 403);
}
}
private function canAccessProject(): bool
{
$user = Auth::user();
return $user->can('manage all')
|| ($this->project && $this->project->users()->where('user_id', $user->id)->exists());
}
#[On('tasksChanged')]
public function refreshTasks(): void
{
// Trigger re-render
}
public function updateTaskStatus(Task $task, string $status): void
{
abort_unless(Auth::user()->can('update', $task), 403);
$oldStatus = $task->status;
$data = ['status' => $status];
if ($oldStatus !== 'completed' && $status === 'completed') {
$data['completed_at'] = now();
$data['completed_by'] = Auth::id();
} elseif ($oldStatus === 'completed' && $status !== 'completed') {
$data['completed_at'] = null;
$data['completed_by'] = null;
}
$task->update($data);
$this->dispatch('tasksChanged');
}
public function updateTaskOrder(int $taskId, int $order): void
{
$task = Task::find($taskId);
if ($task && Auth::user()->can('update', $task)) {
$task->update(['order' => $order]);
}
}
public function resetFilters(): void
{
$this->reset(['search', 'assigneeFilter', 'phaseFilter', 'priorityFilter', 'showOverdueOnly']);
$this->resetPage();
}
public function render()
{
$user = Auth::user();
$baseQuery = Task::with(['project', 'phase', 'assignee', 'creator', 'subtasks'])
->where(function ($q) use ($user) {
if (! $user->can('manage all tasks')) {
$q->whereHas('project', function ($sub) use ($user) {
$sub->whereHas('users', function ($sub2) use ($user) {
$sub2->where('user_id', $user->id);
});
});
}
});
if ($this->project) {
$baseQuery->where('project_id', $this->project->id);
}
if ($this->search) {
$baseQuery->where(function ($q) {
$q->where('title', 'like', '%'.$this->search.'%')
->orWhere('description', 'like', '%'.$this->search.'%');
});
}
if ($this->assigneeFilter) {
$baseQuery->where('assigned_to', $this->assigneeFilter);
}
if ($this->phaseFilter) {
$baseQuery->where('phase_id', $this->phaseFilter);
}
if ($this->priorityFilter) {
$baseQuery->where('priority', $this->priorityFilter);
}
if ($this->showOverdueOnly) {
$baseQuery->overdue();
}
// Get tasks grouped by status
$statuses = ['pending', 'in_progress', 'completed', 'cancelled'];
$columns = [];
foreach ($statuses as $status) {
$query = clone $baseQuery;
$query->where('status', $status)
->orderBy('order')
->orderBy('created_at', 'desc');
$tasks = $query->get();
$columns[$status] = [
'label' => Task::statusOptions()[$status],
'color' => $this->getStatusColor($status),
'tasks' => $tasks,
'count' => $tasks->count(),
];
}
// Filter options
$assignees = User::whereHas('assignedTasks', function ($q) use ($user) {
if (! $user->can('manage all tasks')) {
$q->whereHas('project', function ($sub) use ($user) {
$sub->whereHas('users', function ($sub2) use ($user) {
$sub2->where('user_id', $user->id);
});
});
}
})->get(['id', 'name']);
$phases = $this->project
? $this->project->phases()->get(['id', 'name'])
: collect();
return view('livewire.tasks.task-kanban', [
'columns' => $columns,
'assignees' => $assignees,
'phases' => $phases,
'statusOptions' => Task::statusOptions(),
'priorityOptions' => Task::priorityOptions(),
]);
}
private function getStatusColor(string $status): string
{
return match ($status) {
'pending' => '#6b7280', // gray
'in_progress' => '#3b82f6', // blue
'completed' => '#10b981', // green
'cancelled' => '#ef4444', // red
default => '#6b7280',
};
}
}
+186
View File
@@ -0,0 +1,186 @@
<?php
namespace App\Livewire\Tasks;
use App\Models\Project;
use App\Models\Task;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Livewire\Attributes\Layout;
use Livewire\Attributes\On;
use Livewire\Component;
use Livewire\WithPagination;
#[Layout('layouts.app')]
class TaskManager extends Component
{
use WithPagination;
public ?Project $project = null;
public $search = '';
public $statusFilter = '';
public $priorityFilter = '';
public $assigneeFilter = '';
public $phaseFilter = '';
public $showOverdueOnly = false;
public $perPage = 25;
public $sortField = 'created_at';
public $sortDirection = 'desc';
public $viewMode = 'table'; // 'table' or 'kanban'
protected $queryString = [
'search' => ['except' => ''],
'statusFilter' => ['except' => ''],
'priorityFilter' => ['except' => ''],
'assigneeFilter' => ['except' => ''],
'phaseFilter' => ['except' => ''],
'showOverdueOnly' => ['except' => false],
'perPage' => ['except' => 25],
'sortField' => ['except' => 'created_at'],
'sortDirection' => ['except' => 'desc'],
'viewMode' => ['except' => 'table'],
];
public function mount(?Project $project = null): void
{
$this->project = $project;
if ($project) {
abort_unless($this->canAccessProject() && Auth::user()->can('view tasks'), 403);
} else {
abort_unless(Auth::user()->can('view tasks'), 403);
}
}
private function canAccessProject(): bool
{
$user = Auth::user();
return $user->can('manage all')
|| ($this->project && $this->project->users()->where('user_id', $user->id)->exists());
}
#[On('tasksChanged')]
public function refreshTasks(): void
{
// Trigger re-render
}
public function sortBy(string $field): void
{
if ($this->sortField === $field) {
$this->sortDirection = $this->sortDirection === 'asc' ? 'desc' : 'asc';
} else {
$this->sortField = $field;
$this->sortDirection = 'asc';
}
}
public function resetFilters(): void
{
$this->reset(['search', 'statusFilter', 'priorityFilter', 'assigneeFilter', 'phaseFilter', 'showOverdueOnly']);
$this->resetPage();
}
public function deleteTask(Task $task): void
{
abort_unless(Auth::user()->can('delete', $task), 403);
$task->delete();
session()->flash('message', 'Tarea eliminada');
$this->dispatch('tasksChanged');
}
public function toggleViewMode(): void
{
$this->viewMode = $this->viewMode === 'table' ? 'kanban' : 'table';
}
public function render()
{
$user = Auth::user();
$query = Task::with(['project', 'phase', 'assignee', 'creator', 'subtasks'])
->where(function ($q) use ($user) {
if (! $user->can('manage all tasks')) {
$q->whereHas('project', function ($sub) use ($user) {
$sub->whereHas('users', function ($sub2) use ($user) {
$sub2->where('user_id', $user->id);
});
});
}
});
if ($this->project) {
$query->where('project_id', $this->project->id);
}
if ($this->search) {
$query->where(function ($q) {
$q->where('title', 'like', '%'.$this->search.'%')
->orWhere('description', 'like', '%'.$this->search.'%');
});
}
if ($this->statusFilter) {
$query->where('status', $this->statusFilter);
}
if ($this->priorityFilter) {
$query->where('priority', $this->priorityFilter);
}
if ($this->assigneeFilter) {
$query->where('assigned_to', $this->assigneeFilter);
}
if ($this->phaseFilter) {
$query->where('phase_id', $this->phaseFilter);
}
if ($this->showOverdueOnly) {
$query->overdue();
}
// Sorting
$allowedSorts = ['title', 'status', 'priority', 'due_date', 'created_at', 'order'];
if (in_array($this->sortField, $allowedSorts)) {
$query->orderBy($this->sortField, $this->sortDirection);
} else {
$query->orderBy('order')->orderBy('created_at', 'desc');
}
$tasks = $query->paginate($this->perPage);
// Filter options
$assignees = User::whereHas('assignedTasks', function ($q) use ($user) {
if (! $user->can('manage all tasks')) {
$q->whereHas('project', function ($sub) use ($user) {
$sub->whereHas('users', function ($sub2) use ($user) {
$sub2->where('user_id', $user->id);
});
});
}
})->get(['id', 'name']);
$phases = $this->project
? $this->project->phases()->get(['id', 'name'])
: collect();
return view('livewire.tasks.task-manager', [
'tasks' => $tasks,
'assignees' => $assignees,
'phases' => $phases,
'statusOptions' => Task::statusOptions(),
'priorityOptions' => Task::priorityOptions(),
]);
}
}
+2
View File
@@ -50,6 +50,8 @@ class UserForm extends Component
public array $languages = [
'es' => ['name' => 'Español', 'flag' => 'es.svg'],
'en' => ['name' => 'English', 'flag' => 'gb.svg'],
'fr' => ['name' => 'Français', 'flag' => 'fr.svg'],
'ru' => ['name' => 'Русский', 'flag' => 'ru.svg'],
];
public function mount(?User $user = null): void
+101
View File
@@ -0,0 +1,101 @@
<?php
namespace App\Models;
use App\Notifications\TaskCommentNotification;
use App\Traits\LogsActivity;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\MorphTo;
class Comment extends Model
{
use HasFactory, LogsActivity;
protected $fillable = [
'commentable_type',
'commentable_id',
'user_id',
'body',
'parent_id',
];
protected $casts = [
'body' => 'string',
];
// ============================================================
// Events / Observers
// ============================================================
protected static function booted(): void
{
static::created(function (Comment $comment) {
// Notify if comment is on a Task
if ($comment->commentable_type === Task::class) {
$task = $comment->commentable;
if ($task) {
// Notify creator and assignee (except the commenter)
$usersToNotify = collect([$task->creator, $task->assignee])
->unique('id')
->filter(fn ($u) => $u && $u->id !== $comment->user_id);
foreach ($usersToNotify as $user) {
$user->notify(new TaskCommentNotification($task, $comment));
}
}
}
});
}
// ============================================================
// Relationships
// ============================================================
public function commentable(): MorphTo
{
return $this->morphTo();
}
public function user(): BelongsTo
{
return $this->belongsTo(User::class);
}
public function parent(): BelongsTo
{
return $this->belongsTo(Comment::class, 'parent_id');
}
public function replies(): HasMany
{
return $this->hasMany(Comment::class, 'parent_id')->orderBy('created_at');
}
// ============================================================
// Scopes
// ============================================================
public function scopeTopLevel($query)
{
return $query->whereNull('parent_id');
}
public function scopeWithReplies($query)
{
return $query->with('replies.user');
}
// ============================================================
// Accessors
// ============================================================
public function getExcerptAttribute(): string
{
return strlen($this->body) > 150
? substr($this->body, 0, 150).'...'
: $this->body;
}
}
+8
View File
@@ -10,6 +10,14 @@ class Inspection extends Model
{
use SoftDeletes, LogsActivity;
protected static function booted(): void
{
static::deleting(function ($inspection) {
// Cascada: borrar media asociado cuando se elimina la inspección
$inspection->media()->get()->each->delete();
});
}
const STATUSES = ['pending', 'in_progress', 'completed', 'approved', 'rejected'];
const RESULTS = ['pass', 'fail', 'conditional'];
+49 -12
View File
@@ -1,5 +1,7 @@
<?php
namespace App\Models;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;
@@ -9,28 +11,63 @@ class Phase extends Model
protected $fillable = [
'project_id', 'name', 'description', 'order', 'color', 'progress_percent',
'planned_start', 'planned_end', 'actual_start', 'actual_end'
'planned_start', 'planned_end', 'actual_start', 'actual_end',
];
protected $casts = [
'planned_start' => 'date',
'planned_end' => 'date',
'actual_start' => 'date',
'actual_end' => 'date',
'planned_end' => 'date',
'actual_start' => 'date',
'actual_end' => 'date',
];
public function project() { return $this->belongsTo(Project::class); }
public function layers() { return $this->hasMany(Layer::class); }
public function progressUpdates() { return $this->hasMany(ProgressUpdate::class); }
public function currentLayer() { return $this->hasOne(Layer::class)->latestOfMany(); }
public function features() { return $this->hasManyThrough(Feature::class, Layer::class); }
public function media() { return $this->morphMany(Media::class, 'mediable'); }
public function images() { return $this->morphMany(Media::class, 'mediable')->where('category', 'image'); }
public function project()
{
return $this->belongsTo(Project::class);
}
public function layers()
{
return $this->hasMany(Layer::class);
}
public function progressUpdates()
{
return $this->hasMany(ProgressUpdate::class);
}
public function currentLayer()
{
return $this->hasOne(Layer::class)->latestOfMany();
}
public function features()
{
return $this->hasManyThrough(Feature::class, Layer::class);
}
public function media()
{
return $this->morphMany(Media::class, 'mediable');
}
public function images()
{
return $this->morphMany(Media::class, 'mediable')->where('category', 'image');
}
public function tasks()
{
return $this->hasMany(Task::class);
}
public function getDeviationDaysAttribute(): ?int
{
if (!$this->planned_end) return null;
if (! $this->planned_end) {
return null;
}
$end = $this->actual_end ?? now();
return $this->planned_end->diffInDays($end, false);
}
}
+11 -5
View File
@@ -16,8 +16,8 @@ class Project extends Model
];
protected $casts = [
"start_date" => "date",
"end_date_estimated" => "date",
'start_date' => 'date',
'end_date_estimated' => 'date',
];
public function changeOrders()
@@ -44,8 +44,8 @@ class Project extends Model
public function companies()
{
return $this->belongsToMany(Company::class, 'company_project')
->withPivot('role_in_project')
->withTimestamps();
->withPivot('role_in_project')
->withTimestamps();
}
public function creator()
@@ -69,14 +69,20 @@ class Project extends Model
return $this->morphMany(Media::class, 'mediable')->where('category', 'image');
}
public function tasks()
{
return $this->hasMany(Task::class);
}
// Scope to filter accessible projects for non-admin users
public function scopeAccessibleBy($query, User $user)
{
if ($user->can('manage all')) {
return $query;
}
return $query->whereHas('users', function ($q) use ($user) {
$q->where('user_id', $user->id);
});
}
}
}
+326
View File
@@ -0,0 +1,326 @@
<?php
namespace App\Models;
use App\Notifications\TaskAssignedNotification;
use App\Notifications\TaskStatusChangedNotification;
use App\Traits\LogsActivity;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\Relations\BelongsTo;
use Illuminate\Database\Eloquent\Relations\HasMany;
use Illuminate\Database\Eloquent\Relations\MorphMany;
use Illuminate\Database\Eloquent\SoftDeletes;
class Task extends Model
{
use HasFactory, LogsActivity, SoftDeletes;
protected $fillable = [
'project_id',
'phase_id',
'parent_task_id',
'title',
'description',
'status',
'priority',
'created_by',
'assigned_to',
'due_date',
'start_date',
'completed_at',
'completed_by',
'estimated_hours',
'actual_hours',
'order',
'uuid',
'client_updated_at',
];
protected $casts = [
'due_date' => 'date',
'start_date' => 'date',
'completed_at' => 'datetime',
'estimated_hours' => 'integer',
'actual_hours' => 'integer',
'order' => 'integer',
];
// ============================================================
// Events / Observers
// ============================================================
protected static function booted(): void
{
static::created(function (Task $task) {
if ($task->assigned_to) {
$assignee = $task->assignee;
if ($assignee && $assignee->id !== auth()->id()) {
$assignee->notify(new TaskAssignedNotification($task));
}
}
});
static::updated(function (Task $task) {
// Notify on assignment change
if ($task->isDirty('assigned_to')) {
$newAssigneeId = $task->assigned_to;
if ($newAssigneeId) {
$assignee = User::find($newAssigneeId);
if ($assignee && $assignee->id !== auth()->id()) {
$assignee->notify(new TaskAssignedNotification($task));
}
}
}
// Notify on status change
if ($task->isDirty('status')) {
$oldStatus = $task->getOriginal('status');
$task->creator?->notify(new TaskStatusChangedNotification($task, $oldStatus));
if ($task->assigned_to && $task->assigned_to !== $task->created_by) {
$task->assignee?->notify(new TaskStatusChangedNotification($task, $oldStatus));
}
}
});
}
// ============================================================
// Relationships
// ============================================================
public function project(): BelongsTo
{
return $this->belongsTo(Project::class);
}
public function phase(): BelongsTo
{
return $this->belongsTo(Phase::class);
}
public function parent(): BelongsTo
{
return $this->belongsTo(Task::class, 'parent_task_id');
}
public function subtasks(): HasMany
{
return $this->hasMany(Task::class, 'parent_task_id')->orderBy('order')->orderBy('id');
}
public function creator(): BelongsTo
{
return $this->belongsTo(User::class, 'created_by');
}
public function assignee(): BelongsTo
{
return $this->belongsTo(User::class, 'assigned_to');
}
public function completer(): BelongsTo
{
return $this->belongsTo(User::class, 'completed_by');
}
public function media(): MorphMany
{
return $this->morphMany(Media::class, 'mediable');
}
public function comments(): MorphMany
{
return $this->morphMany(Comment::class, 'commentable')->orderBy('created_at');
}
public function activityLogs(): MorphMany
{
return $this->morphMany(ActivityLog::class, 'model');
}
// ============================================================
// Scopes
// ============================================================
public function scopePending($query)
{
return $query->where('status', 'pending');
}
public function scopeInProgress($query)
{
return $query->where('status', 'in_progress');
}
public function scopeCompleted($query)
{
return $query->where('status', 'completed');
}
public function scopeCancelled($query)
{
return $query->where('status', 'cancelled');
}
public function scopeNotCompleted($query)
{
return $query->where('status', '!=', 'completed');
}
public function scopeOverdue($query)
{
return $query->where('status', '!=', 'completed')
->whereNotNull('due_date')
->whereDate('due_date', '<', now()->toDateString());
}
public function scopeDueToday($query)
{
return $query->where('status', '!=', 'completed')
->whereDate('due_date', now()->toDateString());
}
public function scopeAccessibleBy($query, User $user)
{
if ($user->can('manage all tasks')) {
return $query;
}
return $query->whereHas('project', function ($q) use ($user) {
$q->whereHas('users', function ($sub) use ($user) {
$sub->where('user_id', $user->id);
});
});
}
// ============================================================
// Accessors / Helpers
// ============================================================
public function getIsOverdueAttribute(): bool
{
return $this->status !== 'completed'
&& $this->due_date
&& $this->due_date->isPast();
}
public function getIsDueTodayAttribute(): bool
{
return $this->status !== 'completed'
&& $this->due_date
&& $this->due_date->isToday();
}
public function getProgressAttribute(): int
{
$total = $this->subtasks->count();
if ($total === 0) {
return in_array($this->status, ['completed'], true) ? 100 : 0;
}
return (int) round($this->subtasks->where('status', 'completed')->count() / $total * 100);
}
public function getPriorityColorAttribute(): string
{
return match ($this->priority) {
'low' => '#6b7280', // gray
'medium' => '#f59e0b', // amber
'high' => '#ef4444', // red
'critical' => '#7c3aed', // purple
default => '#6b7280',
};
}
public function getStatusColorAttribute(): string
{
return match ($this->status) {
'pending' => '#6b7280', // gray
'in_progress' => '#3b82f6', // blue
'completed' => '#10b981', // green
'cancelled' => '#ef4444', // red
default => '#6b7280',
};
}
public function getStatusLabelAttribute(): string
{
return match ($this->status) {
'pending' => 'Pendiente',
'in_progress' => 'En progreso',
'completed' => 'Completada',
'cancelled' => 'Cancelada',
default => ucfirst((string) $this->status),
};
}
public function getPriorityLabelAttribute(): string
{
return match ($this->priority) {
'low' => 'Baja',
'medium' => 'Media',
'high' => 'Alta',
'critical' => 'Crítica',
default => ucfirst((string) $this->priority),
};
}
// ============================================================
// State Transitions
// ============================================================
public function start(): void
{
$this->update([
'status' => 'in_progress',
'start_date' => $this->start_date ?? now()->toDateString(),
]);
}
public function complete(?User $user = null): void
{
$this->update([
'status' => 'completed',
'completed_at' => now(),
'completed_by' => $user?->id ?? auth()->id(),
]);
}
public function reopen(): void
{
$this->update([
'status' => 'pending',
'completed_at' => null,
'completed_by' => null,
]);
}
public function cancel(): void
{
$this->update(['status' => 'cancelled']);
}
// ============================================================
// Static Helpers
// ============================================================
public static function statusOptions(): array
{
return [
'pending' => 'Pendiente',
'in_progress' => 'En progreso',
'completed' => 'Completada',
'cancelled' => 'Cancelada',
];
}
public static function priorityOptions(): array
{
return [
'low' => 'Baja',
'medium' => 'Media',
'high' => 'Alta',
'critical' => 'Crítica',
];
}
}
+22 -5
View File
@@ -13,7 +13,7 @@ use Spatie\Permission\Traits\HasRoles;
class User extends Authenticatable
{
/** @use HasFactory<UserFactory> */
use HasFactory, Notifiable, HasRoles, HasApiTokens;
use HasApiTokens, HasFactory, HasRoles, Notifiable;
/**
* The attributes that are mass assignable.
@@ -47,16 +47,17 @@ class User extends Authenticatable
{
return [
'email_verified_at' => 'datetime',
'password' => 'hashed',
'valid_from' => 'date',
'valid_until' => 'date',
'password' => 'hashed',
'valid_from' => 'date',
'valid_until' => 'date',
];
}
public function company()
{
return $this->belongsTo(\App\Models\Company::class);
return $this->belongsTo(Company::class);
}
// Many-to-many with projects
public function projects()
{
@@ -68,4 +69,20 @@ class User extends Authenticatable
{
return $this->hasMany(ProgressUpdate::class);
}
// Tasks
public function createdTasks()
{
return $this->hasMany(Task::class, 'created_by');
}
public function assignedTasks()
{
return $this->hasMany(Task::class, 'assigned_to');
}
public function completedTasks()
{
return $this->hasMany(Task::class, 'completed_by');
}
}
@@ -0,0 +1,32 @@
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use App\Models\Inspection;
class InspectionDeletedNotification extends Notification
{
use Queueable;
public function __construct(public Inspection $inspection, public string $deletedBy) {}
public function via($notifiable): array
{
return ['database'];
}
public function toArray($notifiable): array
{
return [
'type' => 'inspection_deleted',
'inspection_id' => $this->inspection->id,
'project_id' => $this->inspection->project_id,
'feature_name' => $this->inspection->feature?->name ?? '—',
'template_name' => $this->inspection->template?->name ?? '—',
'deleted_by' => $this->deletedBy,
'message' => "Inspección eliminada en '{$this->inspection->feature?->name}' por {$this->deletedBy}",
];
}
}
@@ -0,0 +1,33 @@
<?php
namespace App\Notifications;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
use App\Models\Inspection;
class InspectionUpdatedNotification extends Notification
{
use Queueable;
public function __construct(public Inspection $inspection, public array $changes = []) {}
public function via($notifiable): array
{
return ['database'];
}
public function toArray($notifiable): array
{
return [
'type' => 'inspection_updated',
'inspection_id' => $this->inspection->id,
'project_id' => $this->inspection->project_id,
'feature_name' => $this->inspection->feature?->name ?? '—',
'template_name' => $this->inspection->template?->name ?? '—',
'result' => $this->inspection->result,
'changes' => $this->changes,
'message' => "Inspección actualizada en '{$this->inspection->feature?->name}'",
];
}
}
@@ -0,0 +1,30 @@
<?php
namespace App\Notifications;
use App\Models\Task;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
class TaskAssignedNotification extends Notification
{
use Queueable;
public function __construct(public Task $task) {}
public function via($notifiable): array
{
return ['database'];
}
public function toArray($notifiable): array
{
return [
'type' => 'task_assigned',
'task_id' => $this->task->id,
'project_id' => $this->task->project_id,
'priority' => $this->task->priority,
'message' => "Se te ha asignado la tarea '{$this->task->title}'",
];
}
}
@@ -0,0 +1,31 @@
<?php
namespace App\Notifications;
use App\Models\Comment;
use App\Models\Task;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
class TaskCommentNotification extends Notification
{
use Queueable;
public function __construct(public Task $task, public Comment $comment) {}
public function via($notifiable): array
{
return ['database'];
}
public function toArray($notifiable): array
{
return [
'type' => 'task_comment',
'task_id' => $this->task->id,
'project_id' => $this->task->project_id,
'comment_id' => $this->comment->id,
'message' => "Nuevo comentario en '{$this->task->title}' por {$this->comment->user->name}: ".substr($this->comment->body, 0, 100),
];
}
}
@@ -0,0 +1,30 @@
<?php
namespace App\Notifications;
use App\Models\Task;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
class TaskOverdueNotification extends Notification
{
use Queueable;
public function __construct(public Task $task) {}
public function via($notifiable): array
{
return ['database'];
}
public function toArray($notifiable): array
{
return [
'type' => 'task_overdue',
'task_id' => $this->task->id,
'project_id' => $this->task->project_id,
'due_date' => $this->task->due_date?->toDateString(),
'message' => "Tarea vencida: '{$this->task->title}' (venció el {$this->task->due_date?->format('d/m/Y')})",
];
}
}
@@ -0,0 +1,45 @@
<?php
namespace App\Notifications;
use App\Models\Task;
use Illuminate\Bus\Queueable;
use Illuminate\Notifications\Notification;
class TaskStatusChangedNotification extends Notification
{
use Queueable;
public function __construct(public Task $task, public string $oldStatus) {}
public function via($notifiable): array
{
return ['database'];
}
public function toArray($notifiable): array
{
$label = [
'pending' => 'pendiente',
'in_progress' => 'en progreso',
'completed' => 'completada',
'cancelled' => 'cancelada',
][$this->task->status] ?? $this->task->status;
$oldLabel = [
'pending' => 'pendiente',
'in_progress' => 'en progreso',
'completed' => 'completada',
'cancelled' => 'cancelada',
][$this->oldStatus] ?? $this->oldStatus;
return [
'type' => 'task_status_changed',
'task_id' => $this->task->id,
'project_id' => $this->task->project_id,
'old_status' => $this->oldStatus,
'new_status' => $this->task->status,
'message' => "La tarea '{$this->task->title}' cambió de {$oldLabel} a {$label}",
];
}
}
+122
View File
@@ -0,0 +1,122 @@
<?php
namespace App\Policies;
use App\Models\Task;
use App\Models\User;
class TaskPolicy
{
/**
* Determine whether the user can view any tasks.
*/
public function viewAny(User $user): bool
{
return $user->can('view tasks') || $user->can('manage all tasks');
}
/**
* Determine whether the user can view the task.
*/
public function view(User $user, Task $task): bool
{
if ($user->can('manage all tasks')) {
return true;
}
if (! $user->can('view tasks')) {
return false;
}
return $task->project->users()->where('user_id', $user->id)->exists();
}
/**
* Determine whether the user can create tasks.
*/
public function create(User $user, $project = null): bool
{
if ($user->can('manage all tasks')) {
return true;
}
if (! $user->can('create tasks')) {
return false;
}
if ($project) {
return $project->users()->where('user_id', $user->id)->exists();
}
return true;
}
/**
* Determine whether the user can update the task.
*/
public function update(User $user, Task $task): bool
{
if ($user->can('manage all tasks')) {
return true;
}
if (! $user->can('edit tasks')) {
return false;
}
// Own tasks or tasks in own projects
return $task->created_by === $user->id
|| $task->project->users()->where('user_id', $user->id)->exists();
}
/**
* Determine whether the user can delete the task.
*/
public function delete(User $user, Task $task): bool
{
if ($user->can('manage all tasks')) {
return true;
}
if (! $user->can('delete tasks')) {
return false;
}
// Only creator or project admin can delete
return $task->created_by === $user->id
|| $task->project->users()->where('user_id', $user->id)->wherePivot('role_in_project', 'admin')->exists();
}
/**
* Determine whether the user can assign/reassign the task.
*/
public function assign(User $user, Task $task): bool
{
if ($user->can('manage all tasks')) {
return true;
}
if (! $user->can('assign tasks')) {
return false;
}
return $task->project->users()->where('user_id', $user->id)->exists();
}
/**
* Determine whether the user can restore the task.
*/
public function restore(User $user, Task $task): bool
{
if ($user->can('manage all tasks')) {
return true;
}
if (! $user->can('edit tasks')) {
return false;
}
return $task->project->users()->where('user_id', $user->id)->exists();
}
/**
* Determine whether the user can permanently delete the task.
*/
public function forceDelete(User $user, Task $task): bool
{
return $user->can('manage all tasks');
}
}
+6 -1
View File
@@ -2,8 +2,10 @@
namespace App\Providers;
use Illuminate\Support\ServiceProvider;
use App\Models\Task;
use App\Policies\TaskPolicy;
use Illuminate\Support\Facades\Gate;
use Illuminate\Support\ServiceProvider;
class AppServiceProvider extends ServiceProvider
{
@@ -20,6 +22,9 @@ class AppServiceProvider extends ServiceProvider
*/
public function boot(): void
{
// Register policies
Gate::policy(Task::class, TaskPolicy::class);
// Super-admin bypass: anyone with the "manage all" permission
// (the Admin role has it) passes every authorization check.
// Return true to allow, or null to let normal checks run — never false.