270 lines
15 KiB
PHP
Executable File
270 lines
15 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)
|
|
{
|
|
//Recebe o User pela sessao atual e recebe seus dados.
|
|
$userEmail = Auth::user()->email;
|
|
$receiveDataEmail = User::where('email', $userEmail)->first();
|
|
$receiveDataWs = ConstructionWorkstation::where('name_workstations', $receiveDataEmail->user_name)->first();
|
|
|
|
|
|
// Verifica equipamentos que tenho 2 dados com o departure_date = NULL e especificamente um dado tem o elemental_tasks_id = 9 e o outro igual a NULL.
|
|
//Isto para ser possivel identificar equipamentos (psv-Provavelmente) que esta sendo feitas em simultanio suas pecas e nao deve ser diponivel ate uma de suas pecas tiverem deponivel.
|
|
$excludedEquipmentsQuery = ControlEquipmentWorkstation::select('equipmentWorkHistorys_id')
|
|
->whereNull('departure_date')
|
|
->where('status', 1)
|
|
->groupBy('equipmentWorkHistorys_id')
|
|
->havingRaw('SUM(CASE WHEN elemental_tasks_id = 9 THEN 1 ELSE 0 END) = 1') // Assegura um registro com elemental_tasks_id = 9
|
|
->havingRaw('SUM(CASE WHEN elemental_tasks_id IS NULL THEN 1 ELSE 0 END) = 1') // Assegura um registro com elemental_tasks_id NULL
|
|
->pluck('equipmentWorkHistorys_id'); // Obtém os IDs para exclusão
|
|
|
|
|
|
// // Busca todos os equipamentos associados a um determinado projeto.
|
|
// $receiveAllEquipmentOfProject = Equipment::where('company_projects_id', $receiveDataWs->company_projects_id)
|
|
|
|
// ->WhereHas('equipmentWorkHistory.controlEquipmentWorkstation', function ($subQuery) use ($excludedEquipmentsQuery) {
|
|
// $subQuery->whereNot('equipmentWorkHistorys_id', $excludedEquipmentsQuery);
|
|
// })
|
|
// // Primeiro filtro: Equipamentos sem ocorrência em ControlEquipmentWorkstation
|
|
// ->whereDoesntHave('equipmentWorkHistory.controlEquipmentWorkstation')
|
|
|
|
// // Segundo filtro: Equipamentos que ja tiverem um controlEquipmentWorkstation_ID criado uma dos Ws o fechou sem concluir por um metodo nao convencional e o script do servidor limpou o controlEquipmentWorkstation_ID
|
|
// ->orWhereHas('equipmentWorkHistory.controlEquipmentWorkstation', function ($subQuery) {
|
|
// $subQuery->whereNull('id_workstations')
|
|
// ->whereNull('elemental_tasks_id')
|
|
// ->whereNull('departure_date')
|
|
// ->where('status', 0);
|
|
// })
|
|
// // Terceiro filtro: Equipamentos com todas as colunas sao prenchidas como deve ser, signifca que e uma tarefa concluida(finalizada) e agora vai criar um novo dado na controlEquipmentWorkstation para a proxima tarefa.
|
|
// ->orWhereHas('equipmentWorkHistory.controlEquipmentWorkstation', function ($subQuery) {
|
|
// $subQuery->whereNotNull('id_workstations')
|
|
// ->where(function ($innerQuery) {
|
|
// $innerQuery->whereNotNull('elemental_tasks_id')
|
|
// ->whereNotNull('departure_date')
|
|
// ->where('status', 1);
|
|
// });
|
|
// })
|
|
|
|
// // No geral esta condicao verifica que e uma psv, e que tem a possiblidade de ficar diponivel para selecionar o equipamento , mesmo com ele ja dentro de uma Ws.
|
|
// // Adiciona condição para PSV (equipment_type_id = 3)
|
|
// ->orWhere(function ($query) {
|
|
// // Verifica no sistema se for uma 'PSV' , mesmo apos entrar como @Corpo, ou pelo @Obutador deve deixar o outro disponivel.
|
|
// $query->whereHas('equipmentType', function ($typeQuery) {
|
|
// $typeQuery->where('equipment_type_id', 3);
|
|
// })
|
|
// ->whereHas('equipmentWorkHistory.controlEquipmentWorkstation', function ($subQuery) {
|
|
// $subQuery->where('status', 1)
|
|
// ->whereNull('departure_date')
|
|
// ->where(function ($taskQuery) {
|
|
// $taskQuery->where('elemental_tasks_id', 9)
|
|
// ->orWhereNull('elemental_tasks_id');
|
|
// });
|
|
// });
|
|
// })
|
|
// // Último filtro: Equipamentos cujo equipmentWorkHistorys_id NÃO estão na lista excluída.
|
|
// ->whereDoesntHave('equipmentWorkHistory.controlEquipmentWorkstation', function ($subQuery) use ($excludedEquipmentsQuery) {
|
|
// // Aqui é onde verificamos se o equipmentWorkHistorys_id NÃO está contido na lista excluída.
|
|
// $subQuery->whereIn('equipmentWorkHistorys_id', $excludedEquipmentsQuery);
|
|
// })
|
|
// ->get()
|
|
// ->map(function ($equipment) {
|
|
// if (!$equipment->equipmentWorkHistory->isEmpty()) {
|
|
// $equipmentWorkHistory = $equipment->equipmentWorkHistory->first();
|
|
// $equipment->equipmentWorkHistoryId = $equipmentWorkHistory->equipmentWorkHistorys_id;
|
|
// } else {
|
|
// $equipment->equipmentWorkHistoryId = null;
|
|
// }
|
|
// return $equipment;
|
|
// });
|
|
|
|
|
|
// Busca todos os equipamentos associados a um determinado projeto.
|
|
$receiveAllEquipmentOfProject = Equipment::where('company_projects_id', $receiveDataWs->company_projects_id)
|
|
// Use whereDoesntHave para excluir os equipamentos cujos IDs de histórico estão no array excluído
|
|
->where(function ($query) use ($excludedEquipmentsQuery) {
|
|
// Agrupa as condições para aplicar corretamente a lógica de exclusão e inclusão
|
|
$query->whereDoesntHave('equipmentWorkHistory.controlEquipmentWorkstation', function ($subQuery) use ($excludedEquipmentsQuery) {
|
|
// Exclui os equipamentos cujos IDs de histórico estão no array excluído
|
|
$subQuery->whereIn('equipmentWorkHistorys_id', $excludedEquipmentsQuery);
|
|
})
|
|
->orWhere(function ($query) {
|
|
// Aplica o segundo filtro somente aos equipamentos que não foram excluídos pelo primeiro
|
|
$query->whereHas('equipmentWorkHistory.controlEquipmentWorkstation', function ($subQuery) {
|
|
$subQuery->whereNotNull('id_workstations')
|
|
->whereNotNull('elemental_tasks_id')
|
|
->whereNotNull('departure_date')
|
|
->where('status', 1);
|
|
});
|
|
|
|
// Verifica no sistema se for uma 'PSV' , mesmo apos entrar como @Corpo, ou pelo @Obutador deve deixar o outro disponivel.
|
|
$query->whereHas('equipmentType', function ($typeQuery) {
|
|
$typeQuery->where('equipment_type_id', 3);
|
|
})
|
|
->whereHas('equipmentWorkHistory.controlEquipmentWorkstation', function ($subQuery) {
|
|
$subQuery->where('status', 1)
|
|
->whereNull('departure_date')
|
|
->where(function ($taskQuery) {
|
|
$taskQuery->where('elemental_tasks_id', 9)
|
|
->orWhereNull('elemental_tasks_id');
|
|
});
|
|
});
|
|
});
|
|
// Primeiro filtro: Equipamentos sem ocorrência em ControlEquipmentWorkstation
|
|
$query->whereDoesntHave('equipmentWorkHistory.controlEquipmentWorkstation');
|
|
|
|
// Segundo filtro: Equipamentos que ja tiverem um controlEquipmentWorkstation_ID criado uma dos Ws o fechou sem concluir por um metodo nao convencional e o script do servidor limpou o controlEquipmentWorkstation_ID
|
|
$query->orWhereHas('equipmentWorkHistory.controlEquipmentWorkstation', function ($subQuery) {
|
|
$subQuery->whereNull('id_workstations')
|
|
->whereNull('elemental_tasks_id')
|
|
->whereNull('departure_date')
|
|
->where('status', 0);
|
|
});
|
|
})
|
|
->with('equipmentWorkHistory') // Carrega o relacionamento equipmentWorkHistory
|
|
->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
|
|
|
|
// Inicializa um array para armazenar o status de cada equipamento
|
|
$equipmentStatus = [];
|
|
|
|
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
|
|
}
|
|
|
|
// Busca registros na ControlEquipmentWorkstation com base no equipmentWorkHistoryId
|
|
$controlRecords = ControlEquipmentWorkstation::where('equipmentWorkHistorys_id', $workHistoryId)->get();
|
|
|
|
if ($controlRecords->isEmpty()) {
|
|
// Se não houver registros, considera como valor 0 (nenhuma tarefa ativa)
|
|
$equipmentStatus[$equipment->equipment_id] = 0;
|
|
} else {
|
|
//Deve verificar se o departure_date e NULL e o id_workstations <> null, e status = 0
|
|
// $activeTasks = $controlRecords->whereNull('departure_date');
|
|
$activeTasks = $controlRecords->whereNull('departure_date')
|
|
->whereNotNull('id_workstations')
|
|
->where('status', '!=', 0);
|
|
|
|
if ($activeTasks->isEmpty()) {
|
|
// Se não houver tarefas ativas, considera como valor 0 (nenhuma tarefa ativa)
|
|
$equipmentStatus[$equipment->equipment_id] = 0;
|
|
} else {
|
|
// Verifica as condições para determinar os valores 1 ou 2
|
|
$hasObturadorTask = $activeTasks->contains('elemental_tasks_id', 9);
|
|
$hasCorpoTask = $activeTasks->contains('elemental_tasks_id', null);
|
|
|
|
if ($hasObturadorTask) {
|
|
// Se tiver tarefa ativa para Obturador, valor = 2
|
|
$equipmentStatus[$equipment->equipment_id] = 2;
|
|
} elseif ($hasCorpoTask) {
|
|
// Se tiver tarefa ativa para Corpo, valor = 1
|
|
$equipmentStatus[$equipment->equipment_id] = 1;
|
|
} else {
|
|
// Caso contrário, considera como 0
|
|
$equipmentStatus[$equipment->equipment_id] = 0;
|
|
}
|
|
}
|
|
}
|
|
|
|
$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 = array_keys($equipmentStatus);
|
|
|
|
|
|
|
|
// Obtendo os registros QrcodesAssociatedEquipment para esses equipamentos
|
|
$receiveQrcodeEquipmentsProject = QrcodesAssociatedEquipment::whereIn('equipment_id', $equipmentIds)
|
|
->get();
|
|
|
|
|
|
$filteredQrcodeEquipments = $receiveQrcodeEquipmentsProject->filter(function ($qrcodeEquipment) use ($equipmentStatus) {
|
|
// Exclui 'Flange'
|
|
if (strpos($qrcodeEquipment->component_tag, '@Flange') !== false) {
|
|
return false;
|
|
}
|
|
|
|
|
|
|
|
// Obtém o status do equipamento atual
|
|
$equipmentId = $qrcodeEquipment->equipment_id;
|
|
$status = $equipmentStatus[$equipmentId] ?? null;
|
|
|
|
// Decide se 'Corpo' ou 'Obturador' deve ser excluído com base no status
|
|
switch ($status) {
|
|
case 1: // Exclui 'Corpo' se o status for 1
|
|
return strpos($qrcodeEquipment->component_tag, '@Corpo') === false;
|
|
case 2: // Exclui 'Obturador' se o status for 2
|
|
return strpos($qrcodeEquipment->component_tag, '@Obturador') === false;
|
|
case 0: // Mantém ambos se o status for 0
|
|
default:
|
|
return true;
|
|
}
|
|
});
|
|
|
|
//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,
|
|
]);
|
|
|
|
}
|
|
}
|