ispt4.0_laravel/app/Http/ViewComposers/WorkstationComposer.php
2024-03-04 16:45:31 +00:00

198 lines
10 KiB
PHP
Executable File

<?php
namespace App\Http\ViewComposers;
use App\Models\ConstructionWorkstation;
use App\Models\ControlEquipmentWorkstation;
use App\Models\Equipment;
use App\Models\EquipmentWorkHistory;
use App\Models\OrderEquipmentTasks;
use App\Models\QrcodesAssociatedEquipment;
use App\Models\User;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\DB;
use Illuminate\View\View;
class WorkstationComposer
{
public function compose(View $view)
{
$userEmail = Auth::user()->email;
$receiveDataEmail = User::where('email', $userEmail)->first();
$receiveDataWs = ConstructionWorkstation::where('name_workstations', $receiveDataEmail->user_name)->first();
// Busca todos os equipamentos associados a um determinado projeto.
// $receiveAllEquipmentOfProject = Equipment::where('company_projects_id', $receiveDataWs->company_projects_id)
// // Verifica se existe histórico de trabalho associado ao equipamento e ao projeto específico.
// ->whereHas('equipmentWorkHistory', function ($query) use ($receiveDataWs) {
// $query->where('company_projects_id', $receiveDataWs->company_projects_id);
// })
// // Exclui os equipamentos cujo histórico de trabalho mais recente (controlEquipmentWorkstation) tem 'elemental_tasks_id' e 'departure_date' nulos.
// ->whereDoesntHave('equipmentWorkHistory.controlEquipmentWorkstation', function ($query) {
// $query->where(function ($q) {
// $q->whereNull('elemental_tasks_id')
// ->WhereNull('departure_date')
// ->WhereNotNull('id_workstations');
// }) ;
// })
// // Carrega o histórico de trabalho associado ao equipamento e ao projeto específico.
// ->with([
// 'equipmentWorkHistory' => function ($query) use ($receiveDataWs) {
// // Filtra o histórico de trabalho pelo 'company_projects_id' para obter os registros relevantes.
// $query->where('company_projects_id', $receiveDataWs->company_projects_id)
// ->select('equipment_id', 'equipmentWorkHistorys_id'); // Seleciona apenas os campos necessários.
// }
// ])
// ->get() // Obtém os resultados da consulta.
// ->map(function ($equipment) {
// // Supondo que cada equipamento tem apenas um 'equipmentWorkHistory' relevante para este contexto
// if (!$equipment->equipmentWorkHistory->isEmpty()) {
// $equipmentWorkHistory = $equipment->equipmentWorkHistory->first();
// $equipment->equipmentWorkHistoryId = $equipmentWorkHistory->equipmentWorkHistorys_id;
// } else {
// // Definir como null ou algum valor padrão se não houver histórico correspondente
// $equipment->equipmentWorkHistoryId = null;
// }
// return $equipment;
// });
// $receiveAllEquipmentOfProject = Equipment::where('company_projects_id', $receiveDataWs->company_projects_id)
// // Primeiro filtro: Equipamentos sem ocorrência em ControlEquipmentWorkstation
// ->whereDoesntHave('equipmentWorkHistory.controlEquipmentWorkstation')
// // Segundo filtro: Equipamentos com ocorrências onde id_workstations e elemental_tasks_id são nulos
// ->orWhereHas('equipmentWorkHistory.controlEquipmentWorkstation', function ($query) {
// $query->whereNull('id_workstations')
// ->whereNull('elemental_tasks_id');
// })
// // Terceiro filtro: Equipamentos com todas as ocorrências onde id_workstations, elemental_tasks_id e departure_date não são nulos
// ->orWhereHas('equipmentWorkHistory.controlEquipmentWorkstation', function ($query) {
// $query->whereNotNull('id_workstations')
// ->whereNotNull('elemental_tasks_id')
// ->whereNotNull('departure_date');
// })
// // Carrega o histórico de trabalho associado ao equipamento e ao projeto específico
// ->with([
// 'equipmentWorkHistory' => function ($query) use ($receiveDataWs) {
// $query->where('company_projects_id', $receiveDataWs->company_projects_id)
// ->select('equipment_id', 'equipmentWorkHistorys_id');
// }
// ])
// ->get()
// ->map(function ($equipment) {
// if (!$equipment->equipmentWorkHistory->isEmpty()) {
// $equipmentWorkHistory = $equipment->equipmentWorkHistory->first();
// $equipment->equipmentWorkHistoryId = $equipmentWorkHistory->equipmentWorkHistorys_id;
// } else {
// $equipment->equipmentWorkHistoryId = null;
// }
// return $equipment;
// });
$receiveAllEquipmentOfProject = Equipment::where('company_projects_id', $receiveDataWs->company_projects_id)
->where(function ($query) use ($receiveDataWs) {
// Primeiro filtro: Equipamentos sem ocorrência em ControlEquipmentWorkstation
$query->whereDoesntHave('equipmentWorkHistory.controlEquipmentWorkstation');
// Segundo filtro: Equipamentos com ocorrências onde id_workstations e elemental_tasks_id são nulos
$query->orWhereHas('equipmentWorkHistory.controlEquipmentWorkstation', function ($subQuery) {
$subQuery->whereNull('id_workstations')
->whereNull('elemental_tasks_id');
});
// Terceiro filtro: Equipamentos com todas as ocorrências onde id_workstations, elemental_tasks_id e departure_date não são nulos
// Inclui a condição para elemental_tasks_id = 9
$query->orWhereHas('equipmentWorkHistory.controlEquipmentWorkstation', function ($subQuery) {
$subQuery->whereNotNull('id_workstations')
->where(function ($innerQuery) {
$innerQuery->whereNotNull('elemental_tasks_id')
->whereNotNull('departure_date')
->orWhere('elemental_tasks_id', 9); // Inclui equipamentos com elemental_tasks_id = 9 independentemente de outros critérios
});
});
})
->with([
'equipmentWorkHistory' => function ($query) use ($receiveDataWs) {
$query->where('company_projects_id', $receiveDataWs->company_projects_id)
->select('equipment_id', 'equipmentWorkHistorys_id');
}
])
->get()
->map(function ($equipment) {
if (!$equipment->equipmentWorkHistory->isEmpty()) {
$equipmentWorkHistory = $equipment->equipmentWorkHistory->first();
$equipment->equipmentWorkHistoryId = $equipmentWorkHistory->equipmentWorkHistorys_id;
} else {
$equipment->equipmentWorkHistoryId = null;
}
return $equipment;
});
$completedEquipments = collect(); // Coleção para armazenar equipamentos concluídos
foreach ($receiveAllEquipmentOfProject as $equipment) {
// Agora 'equipmentWorkHistoryId' contém um único ID, então não usamos 'pluck'
$workHistoryId = $equipment->equipmentWorkHistoryId; // Obter ID do histórico de trabalho diretamente
// Verifica se existe um workHistoryId antes de prosseguir
if (is_null($workHistoryId)) {
continue; // Se não houver histórico de trabalho, continua para o próximo equipamento
}
$taskIds = OrderEquipmentTasks::where('equipmentWorkHistorys_id', $workHistoryId)
->pluck('elemental_tasks_id'); // Obter IDs de tarefas elementares baseado em um único workHistoryId
if ($taskIds->isEmpty()) {
continue; // Se não houver tarefas, continua para o próximo equipamento
}
$workstationTaskCounts = ControlEquipmentWorkstation::whereIn('elemental_tasks_id', $taskIds)
->select('elemental_tasks_id', DB::raw('count(*) as total'))
->groupBy('elemental_tasks_id')
->pluck('total', 'elemental_tasks_id'); // Contagem de tarefas nas estações de trabalho
// Verificar se todas as tarefas foram concluídas pelo menos uma vez
$allTasksCompleted = $taskIds->every(function ($taskId) use ($workstationTaskCounts) {
return isset ($workstationTaskCounts[$taskId]) && $workstationTaskCounts[$taskId] >= 1;
});
if ($allTasksCompleted && $workstationTaskCounts->count() >= $taskIds->count()) {
$completedEquipments->push($equipment); // Adicionar equipamento à lista de concluídos
}
}
// Remover equipamentos concluídos da coleção original
$receiveAllEquipmentOfProject = $receiveAllEquipmentOfProject->reject(function ($equipment) use ($completedEquipments) {
return $completedEquipments->contains($equipment);
});
$equipmentIds = $receiveAllEquipmentOfProject->pluck('equipment_id');
$receiveQrcodeEquipmentsProject = QrcodesAssociatedEquipment::whereIn('equipment_id', $equipmentIds)->get();
//VAMOS filtrar os valores recebidos e terar todas as correspondencias de Flange, ja nao e uma tag que nao vai entrar no percurso do Equipamento.
$filteredQrcodeEquipments = $receiveQrcodeEquipmentsProject->reject(function ($item) {
return strpos($item->component_tag, '@Flange') !== false;
});
//Returning values of the queries to workstations layout
$view->with([
'receiveAllEquipmentOfProject' => $receiveAllEquipmentOfProject,
// foi alterado para a variavel 'filteredQrcodeEquipments' pois nao tem a necessidade do utilizador selecionar 'Flange'(AINDA NAO !)
'receiveQrcodeEquipmentsProject' => $filteredQrcodeEquipments,
'completedEquipments' => $completedEquipments,
'receiveDataWs' => $receiveDataWs,
]);
}
}