weatherService = $weatherService; } public function index(Request $request) { $projectQuery = $request->query('project'); // Fetch all projects for the selector $projects = Project::orderBy('name') ->get(['id', 'ulid', 'name', 'code', 'status']); // Find selected project (by ULID or ID) $selectedProject = null; if ($projectQuery) { $selectedProject = Project::where('ulid', $projectQuery) ->orWhere('id', $projectQuery) ->first(); } // Fetch Weather $weather = $this->getWeatherData($selectedProject); // Fetch Blockers $blockers = $this->getBlockersData($selectedProject); // Fetch Activities $activities = $this->getActivitiesData($selectedProject); // Fetch Resources $resources = $this->getResourcesData($selectedProject); // Fetch Role-Tailored DB Analytics $user = Auth::user(); $roleAnalytics = $this->getRoleAnalyticsData($user, $selectedProject); return Inertia::render('Dashboard', [ 'projects' => $projects, 'selectedProject' => $selectedProject ? [ 'id' => $selectedProject->id, 'ulid' => $selectedProject->ulid, 'name' => $selectedProject->name, 'code' => $selectedProject->code, 'location' => $selectedProject->location, 'status' => $selectedProject->status?->value ?? $selectedProject->status, ] : null, 'weather' => $weather, 'activities' => $activities, 'blockers' => $blockers, 'resources' => $resources, 'roleAnalytics' => $roleAnalytics, ]); } /** * Resolve weather data for global or project-specific view. */ private function getWeatherData(?Project $project): array { if ($project) { $location = $project->location ?? 'New York, NY'; return $this->weatherService->getWeather($location); } // Global view: use central office location (e.g., Central Depot warehouse address or default) $warehouse = \Modules\MaterialLogistics\Models\Warehouse::where('code', 'WH-CEN-01')->first(); $location = $warehouse->address ?? 'New York, NY'; $weather = $this->weatherService->getWeather($location); $weather['forecast'] = 'Global overview based at Central Depot. ' . $weather['forecast']; return $weather; } /** * Get list of critical blockers from TaskDelays and DailyReportIssues. */ private function getBlockersData(?Project $project): array { $blockersList = []; // 1. Fetch Task Delays $delayQuery = TaskDelay::with('task.project') ->whereHas('task', function ($q) use ($project) { if ($project) { $q->where('project_id', $project->id); } }) ->orderByDesc('delay_date') ->take(10); foreach ($delayQuery->get() as $delay) { $projName = $delay->task->project->name ?? 'Unknown Project'; $projUlid = $delay->task->project->ulid ?? null; $urgency = ($delay->lost_hours >= 8) ? 'critical' : 'high'; // Map reason_type to RFI / Material / Safety / Equipment / Regulatory $type = match ($delay->reason_type?->value ?? $delay->reason_type) { 'supply' => 'Material', 'manpower' => 'Labor', 'equipment' => 'Equipment', 'permit' => 'Regulatory', 'weather' => 'Safety', // weather delays represent safety concerns for high work default => 'RFI', }; $blockersList[] = [ 'id' => 'delay_' . $delay->id, 'project_ulid' => $projUlid, 'task_ulid' => $delay->task->ulid ?? null, 'type' => $type, 'title' => sprintf('[%s] %s: %s', $projName, $delay->task->name, $delay->notes ?? 'Delay recorded'), 'urgency' => $urgency, 'date' => $delay->delay_date?->format('Y-m-d') ?? now()->format('Y-m-d'), ]; } // 2. Fetch Daily Report Issues $issueQuery = DailyReportIssue::with('dailyReport.project') ->whereHas('dailyReport', function ($q) use ($project) { if ($project) { $q->where('project_id', $project->id); } }) ->orderByDesc('created_at') ->take(10); foreach ($issueQuery->get() as $issue) { $projName = $issue->dailyReport->project->name ?? 'Unknown Project'; $projUlid = $issue->dailyReport->project->ulid ?? null; $severity = strtolower($issue->severity ?? 'medium'); $urgency = in_array($severity, ['high', 'critical']) ? 'critical' : 'high'; $type = match (strtolower($issue->category ?? '')) { 'safety' => 'Safety', 'rfi' => 'RFI', 'material' => 'Material', 'equipment' => 'Equipment', default => 'Safety', }; $blockersList[] = [ 'id' => 'issue_' . $issue->id, 'project_ulid' => $projUlid, 'daily_report_id' => $issue->daily_report_id, 'type' => $type, 'title' => sprintf('[%s] %s', $projName, $issue->description ?? $issue->issue_description ?? 'Site Issue reported'), 'urgency' => $urgency, 'status' => $issue->status ?? 'open', 'supervisor_name' => $issue->supervisor_name, 'date' => $issue->created_at?->format('Y-m-d') ?? now()->format('Y-m-d'), ]; } // Sort blockers by critical urgency first, then date descending usort($blockersList, function ($a, $b) { if ($a['urgency'] === 'critical' && $b['urgency'] !== 'critical') { return -1; } if ($b['urgency'] === 'critical' && $a['urgency'] !== 'critical') { return 1; } return strcmp($b['date'], $a['date']); }); // Cap at 6 blockers return array_slice($blockersList, 0, 6); } /** * Fetch activity feed from TaskActivity and DailyReports. */ private function getActivitiesData(?Project $project): array { $activitiesList = []; // 1. Task Activities $taskActivityQuery = TaskActivity::with(['task.project', 'user']) ->whereHas('task', function ($q) use ($project) { if ($project) { $q->where('project_id', $project->id); } }) ->orderByDesc('created_at') ->take(15); foreach ($taskActivityQuery->get() as $act) { $projCode = $act->task->project->code ?? ''; $userName = $act->user->name ?? 'System'; $activitiesList[] = [ 'id' => 'task_act_' . $act->id, 'time' => $act->created_at?->diffForHumans() ?? 'Just now', 'timestamp' => $act->created_at?->timestamp ?? 0, 'title' => sprintf('%s updated %s: %s (%s)', $userName, $act->task->name, $act->description, $projCode), 'status' => $act->type ?? 'info', ]; } // 2. Daily Report Submissions $dailyReportQuery = DailyReport::with(['project', 'user']) ->where(function ($q) use ($project) { if ($project) { $q->where('project_id', $project->id); } }) ->orderByDesc('report_date') ->take(10); foreach ($dailyReportQuery->get() as $report) { $projName = $report->project->name ?? 'Unknown'; $userName = $report->user->name ?? 'Reporter'; $activitiesList[] = [ 'id' => 'report_' . $report->id, 'time' => $report->report_date?->diffForHumans() ?? 'Recently', 'timestamp' => $report->report_date?->timestamp ?? 0, 'title' => sprintf('%s submitted Daily Report %s for %s', $userName, $report->report_number, $projName), 'status' => 'completed', ]; } // 3. Task Status transitions (if no TaskActivity records exist, fetch tasks that changed status recently) if (empty($activitiesList)) { $tasksQuery = Task::with('project') ->where(function ($q) use ($project) { if ($project) { $q->where('project_id', $project->id); } }) ->orderByDesc('updated_at') ->take(5); foreach ($tasksQuery->get() as $task) { $statusLabel = $task->status?->label() ?? $task->status; $activitiesList[] = [ 'id' => 'task_status_' . $task->id, 'time' => $task->updated_at?->diffForHumans() ?? 'Recently', 'timestamp' => $task->updated_at?->timestamp ?? 0, 'title' => sprintf('Task "%s" is in status %s (%s)', $task->name, $statusLabel, $task->project->code ?? ''), 'status' => strtolower($statusLabel) === 'completed' ? 'completed' : 'in_progress', ]; } } // Sort combined list by timestamp descending usort($activitiesList, function ($a, $b) { return $b['timestamp'] <=> $a['timestamp']; }); return array_slice($activitiesList, 0, 10); } /** * Compile deployed labor and current equipment from active project data. */ private function getResourcesData(?Project $project): array { $laborExpected = 0; $laborActual = 0; $trades = []; $equipmentActive = 0; $equipmentMaintenance = 0; $equipmentIdle = 0; $equipmentList = []; // Global resource roll-ups should represent active execution only. // A selected project intentionally narrows the dashboard to that project. $projectIds = $project ? [$project->id] : Project::whereIn('status', ['active', 'planning', 'in_progress']) ->pluck('id') ->toArray(); // Labor totals come from every Daily Report labor entry for the active // project set. This intentionally includes all stored report records. $laborLogs = DailyReportLabor::whereHas('dailyReport', function ($query) use ($projectIds) { $query->whereIn('project_id', $projectIds); })->get(); foreach ($laborLogs as $log) { $laborActual += (int) $log->workers_count; $tradeName = $log->trade ?? 'General Labor'; $trades[$tradeName] = ($trades[$tradeName] ?? 0) + (int) $log->workers_count; } // Read equipment entries from every daily report in the project set. // ResourceSummary must represent all stored daily-report records, not // only the latest report for each project. $reports = DailyReport::whereIn('project_id', $projectIds) ->with('equipment') ->get(); foreach ($reports as $report) { foreach ($report->equipment as $log) { $status = strtolower($log->status ?? 'active'); if (str_contains($status, 'active') || str_contains($status, 'use') || str_contains($status, 'operat')) { $equipmentActive++; $eqStatus = 'active'; } elseif (str_contains($status, 'main') || str_contains($status, 'repair') || str_contains($status, 'break')) { $equipmentMaintenance++; $eqStatus = 'maintenance'; } else { $equipmentIdle++; $eqStatus = 'idle'; } $equipmentList[] = [ 'name' => $log->equipment_name ?? 'Equipment', 'status' => $eqStatus, ]; } } if ($laborActual > 0) { $laborExpected = max($laborActual, (int) ceil($laborActual * 1.15)); } return [ 'labor' => [ 'expected' => $laborExpected, 'actual' => $laborActual, 'trades' => $trades ], 'equipment' => [ 'active' => $equipmentActive, 'maintenance' => $equipmentMaintenance, 'idle' => $equipmentIdle, 'list' => $equipmentList ] ]; } /** * Compute role-tailored analytics metrics from database tables. */ private function getRoleAnalyticsData(?\App\Models\User $user, ?Project $project): array { $roleName = $user ? ($user->roles->first()?->name ?? 'User') : 'User'; $userType = $user->user_type ?? 'employee'; $pQuery = function ($query) use ($project) { if ($project) { $query->where('project_id', $project->id); } }; // 1. Executive / Super Admin / Admin Analytics $invoicesQuery = \Modules\FinancialManagement\Models\FinancialInvoice::query(); if ($project) { $invoicesQuery->where('project_id', $project->id); } $totalBilled = (float) $invoicesQuery->sum('subtotal'); $totalPaid = (float) $invoicesQuery->sum('paid_amount'); $totalRetention = (float) $invoicesQuery->sum('retention_amount'); $pendingApprovalsCount = \Modules\ApprovalWorkflow\Models\ApprovalChain::where('status', 'in_review')->count(); $projectsAnalyticsQuery = Project::query(); if ($project) { $projectsAnalyticsQuery->whereKey($project->id); } $totalProjectsCount = (clone $projectsAnalyticsQuery)->count(); $activeProjectsCount = (clone $projectsAnalyticsQuery) ->whereIn('status', ['planning', 'in_progress']) ->count(); // 2. PM Milestone & Progress Analytics $milestonesQuery = \Modules\TimelineScheduling\Models\Milestone::query(); if ($project) { $milestonesQuery->where('project_id', $project->id); } $totalMilestones = $milestonesQuery->count(); $completedMilestones = (clone $milestonesQuery)->where('status', 'completed')->count(); $inProgressMilestones = (clone $milestonesQuery)->where('status', 'in_progress')->count(); // 3. Subcontractor / Bidding Analytics $bidsQuery = \Modules\BiddingManagement\Models\BidPackage::query(); if ($project) { $bidsQuery->where('project_id', $project->id); } $activeBids = $bidsQuery->count(); $openInvitations = \Modules\BiddingManagement\Models\BidInvitation::where('status', 'sent')->count(); // 4. Warehouse & Technical Inventory $totalItems = \Modules\MasterData\Models\Material::count(); $totalWarehouses = \Modules\MaterialLogistics\Models\Warehouse::count(); $totalDocuments = \Modules\DocumentManagement\Models\Document::count(); $pendingCashAdvances = \Modules\FinancialManagement\Models\CashAdvance::where('status', 'pending')->count(); return [ 'role' => $roleName, 'roles' => $user?->getRoleNames()->values()->all() ?? [], 'user_type' => $userType, 'financials' => [ 'total_billed' => $totalBilled, 'total_paid' => $totalPaid, 'total_retention' => $totalRetention, 'outstanding_balance' => max(0, $totalBilled - $totalPaid), ], 'projects' => [ 'total' => $totalProjectsCount, 'active' => $activeProjectsCount, ], 'approvals' => [ 'pending' => $pendingApprovalsCount, ], 'milestones' => [ 'total' => $totalMilestones, 'completed' => $completedMilestones, 'in_progress' => $inProgressMilestones, 'completion_rate' => $totalMilestones > 0 ? round(($completedMilestones / $totalMilestones) * 100, 1) : 0, ], 'bidding' => [ 'active_packages' => $activeBids, 'open_invitations' => $openInvitations, ], 'logistics' => [ 'catalog_items' => $totalItems, 'warehouses' => $totalWarehouses, 'documents' => $totalDocuments, 'pending_cash_advances' => $pendingCashAdvances, ], ]; } }