744 lines
32 KiB
PHP
Executable File
744 lines
32 KiB
PHP
Executable File
<?php
|
|
|
|
namespace App\Http\Controllers;
|
|
|
|
use App\Models\AmbitsEquipment;
|
|
use App\Models\ControlEquipmentWorkstation;
|
|
use App\Models\ElementalTasks;
|
|
use App\Models\EquipmentAssociationAmbit;
|
|
use App\Models\EquipmentWorkHistory;
|
|
use App\Models\TasksAssociationAmbits;
|
|
use App\Models\Unit;
|
|
use App\Models\workstationsTaskAnswers;
|
|
use Illuminate\Http\Request;
|
|
use Illuminate\Support\Facades\DB;
|
|
|
|
use Yajra\DataTables\Facades\DataTables;
|
|
|
|
use App\Models\Equipment;
|
|
use App\Models\Plant;
|
|
use App\Models\CompanyProject;
|
|
use App\Models\User;
|
|
|
|
use App\Models\OrderEquipmentTasks;
|
|
use App\Models\SpecificAttributesEquipmentType;
|
|
use Illuminate\Support\Facades\Auth;
|
|
|
|
|
|
use App\Models\ConstructionWorkstation;
|
|
use App\Models\EquipmentType;
|
|
use Mockery\Undefined;
|
|
|
|
use PDF;
|
|
|
|
class ProjectoDatacontroller extends Controller
|
|
{
|
|
|
|
public function viewProjectsList($orderProjectID)
|
|
{
|
|
|
|
// // $receiveProjectsForThisOrder = CompanyProject::where('order_project',$orderProjectID)->get();
|
|
// $receiveProjectsForThisOrder = CompanyProject::with(['plant.user'])->where('order_project', $orderProjectID)->get();
|
|
|
|
// return view('projectsClients.viewProjectsList',compact('receiveProjectsForThisOrder','orderProjectID'));
|
|
$receiveProjectsForThisOrder = CompanyProject::with(['plant.user'])
|
|
->where('order_project', $orderProjectID)
|
|
->get();
|
|
|
|
// Coletar todos os usuários em uma coleção separada
|
|
$users = $receiveProjectsForThisOrder->map(function ($project) {
|
|
return $project->plant->user;
|
|
})->unique('user_id'); // Aqui filtramos para ter certeza de que cada user_id é único
|
|
|
|
// Agora, você pode passar tanto os projetos quanto os usuários únicos para a sua view
|
|
return view('projectsClients.viewProjectsList', compact('receiveProjectsForThisOrder', 'users', 'orderProjectID'));
|
|
|
|
}
|
|
public function editEquipmentTasks(Request $request, $equipmentID)
|
|
{
|
|
// dd($request);
|
|
$detailsEquipmentWorkHistory = EquipmentWorkHistory::where('equipment_id', $equipmentID)->first();
|
|
|
|
// Se não selecionar nenhuma tarefas ele devolve um erro , pois e necessario pelo menos uma
|
|
if (!in_array('on', $request->input('ordemTasks'))) {
|
|
return redirect()->back()->with('danger', 'É necessário selecionar pelo menos uma tarefa, Para o Equipamento');
|
|
}
|
|
|
|
$executionOrder = 1;
|
|
|
|
foreach ($request->input('ordemTasks') as $key => $value) {
|
|
$orderEquipmentTask = OrderEquipmentTasks::where('equipmentWorkHistorys_id', $detailsEquipmentWorkHistory->equipmentWorkHistorys_id)
|
|
->where('elemental_tasks_id', $key)
|
|
->first();
|
|
|
|
if ($value == "on") {
|
|
if (!$orderEquipmentTask) {
|
|
$orderEquipmentTask = new OrderEquipmentTasks();
|
|
$orderEquipmentTask->equipmentWorkHistorys_id = $detailsEquipmentWorkHistory->equipmentWorkHistorys_id;
|
|
$orderEquipmentTask->elemental_tasks_id = $key;
|
|
}
|
|
$orderEquipmentTask->execution_order = $executionOrder;
|
|
$orderEquipmentTask->save();
|
|
|
|
$executionOrder++;
|
|
} elseif ($value == "off" && $orderEquipmentTask) {
|
|
$orderEquipmentTask->delete();
|
|
}
|
|
}
|
|
|
|
$executionOrder = 1; // Reinicia a contagem de ordem de execução
|
|
$remainingOrderEquipmentTasks = OrderEquipmentTasks::where('equipmentWorkHistorys_id', $detailsEquipmentWorkHistory->equipmentWorkHistorys_id)
|
|
->orderBy('execution_order', 'asc')
|
|
->get();
|
|
|
|
foreach ($remainingOrderEquipmentTasks as $orderEquipmentTask) {
|
|
$orderEquipmentTask->execution_order = $executionOrder;
|
|
$orderEquipmentTask->save();
|
|
$executionOrder++;
|
|
}
|
|
|
|
$orderTasks = OrderEquipmentTasks::where('equipmentWorkHistorys_id', $detailsEquipmentWorkHistory->equipmentWorkHistorys_id)
|
|
->orderBy('execution_order', 'asc')
|
|
->get();
|
|
|
|
$taskExecutionOrders = [];
|
|
foreach ($orderTasks as $task) {
|
|
$taskExecutionOrders[$task->elemental_tasks_id] = $task->execution_order;
|
|
}
|
|
// dd($orderTasks);
|
|
|
|
return redirect()->back()->with('success', 'As tarefas do equipamento foram atualizado com sucesso');
|
|
|
|
}
|
|
|
|
|
|
public function checkProjectIsptNumber(Request $request, $projectId = null)
|
|
{
|
|
$number = $request->get('number');
|
|
$type = $request->get('type'); // 'ispt' ou 'company'
|
|
|
|
$column = $type == 'ispt' ? 'project_ispt_number' : 'project_company_number';
|
|
|
|
// Inicialmente verifica se o número já existe
|
|
$query = CompanyProject::where($column, $number);
|
|
|
|
if (!is_null($projectId)) {
|
|
// Se $projectId não for nulo, exclui o projeto atual da verificação
|
|
$query->where('company_projects_id', '!=', $projectId);
|
|
}
|
|
|
|
$exists = $query->exists();
|
|
|
|
// Verifica também se o número pertence ao projeto atual sendo editado
|
|
$isCurrentProjectNumber = false;
|
|
if (!is_null($projectId)) {
|
|
$isCurrentProjectNumber = CompanyProject::where('company_projects_id', $projectId)
|
|
->where($column, $number)
|
|
->exists();
|
|
}
|
|
|
|
return response()->json([
|
|
'exists' => $exists,
|
|
'isCurrentProjectNumber' => $isCurrentProjectNumber
|
|
]);
|
|
}
|
|
|
|
|
|
public function showAmbitDetailsProjectHistory($projectID, $equipmentID)
|
|
{
|
|
|
|
$detailsProject = CompanyProject::where('company_projects_id', $projectID)->first();
|
|
$detailsCliente = Plant::where('plant_id', $detailsProject->plant_id)->first();
|
|
$detailsProject->user_id = $detailsCliente->user_id;
|
|
|
|
|
|
$detalsEquipmentWorkProject = EquipmentWorkHistory::where('equipment_id', $equipmentID)
|
|
->where('company_projects_id', $projectID)->first();
|
|
|
|
$detalsEquipment = Equipment::where('equipment_id', $equipmentID)->first();
|
|
|
|
//recebe todos os dados referentes ao equipamento
|
|
// OBS : Porem deveria confirma se a tarefa foi mesmo concluida.
|
|
// $receiveAllTasksHistiory = ControlEquipmentWorkstation::where('equipmentWorkHistorys_id', $detalsEquipmentWorkProject->equipmentWorkHistorys_id)->get();
|
|
|
|
$receiveAllTasksEquipmentInHistory = OrderEquipmentTasks::where('equipmentWorkHistorys_id', $detalsEquipmentWorkProject->equipmentWorkHistorys_id)->get();
|
|
|
|
|
|
$receiveAmbit = EquipmentAssociationAmbit::where('equipmentWorkHistorys_id', $detalsEquipmentWorkProject->equipmentWorkHistorys_id)->first();
|
|
// $tasksAssociatedWithAmbit = TasksAssociationAmbits::where('ambits_equipment_id', $receiveAmbit->ambits_id)->get();
|
|
|
|
$tasksAssociatedWithAmbit = TasksAssociationAmbits::with('elementalTask')
|
|
->where('ambits_equipment_id', $receiveAmbit->ambits_id)
|
|
->get();
|
|
|
|
foreach ($tasksAssociatedWithAmbit as $taskAssociation) {
|
|
if ($taskAssociation->elementalTask) {
|
|
// Adiciona diretamente ao objeto TasksAssociationAmbits
|
|
$taskAssociation->elemental_task_description = $taskAssociation->elementalTask->elemental_tasks_description;
|
|
} else {
|
|
// Defina como null ou algum valor padrão se não houver tarefa elementar associada
|
|
$taskAssociation->elemental_task_description = null;
|
|
}
|
|
}
|
|
$receiveAllTasksHistiory = ControlEquipmentWorkstation::with('workstationsTaskAnswers')
|
|
->where('equipmentWorkHistorys_id', $detalsEquipmentWorkProject->equipmentWorkHistorys_id)
|
|
->whereNotNull('entry_date') // Verifica se 'entry_date' não é null
|
|
->whereNotNull('departure_date') // Verifica se 'departure_date' não é null
|
|
->has('workstationsTaskAnswers') // Garante que haja pelo menos uma 'workstationsTaskAnswers' relacionada
|
|
->get();
|
|
|
|
// dd($receiveAllTasksHistiory);
|
|
|
|
foreach ($receiveAllTasksHistiory as $taskHistory) {
|
|
$taskHistory->cardTypeStyle = 'gray'; // Adiciona o campo 'cardTypeStyle'
|
|
|
|
// Obtém o primeiro registro de workstationsTaskAnswers ou define como null se não existir
|
|
$workstationTaskAnswer = $taskHistory->workstationsTaskAnswers->first();
|
|
|
|
if ($workstationTaskAnswer && $workstationTaskAnswer->answer_json) {
|
|
// Decodifica o JSON para um array
|
|
$answersArray = json_decode($workstationTaskAnswer->answer_json, true);
|
|
|
|
// Cria um array associativo onde as chaves são as perguntas e os valores são as respostas
|
|
$formattedAnswers = [];
|
|
foreach ($answersArray as $item) {
|
|
if (isset($item['question']) && isset($item['value'])) {
|
|
$formattedAnswers[$item['question']] = $item['value'];
|
|
}
|
|
}
|
|
|
|
// Atribui o array formatado ao taskHistory
|
|
$taskHistory->formatted_answers = $formattedAnswers;
|
|
} else {
|
|
// Se não houver respostas, define formatted_answers como um array vazio ou null
|
|
$taskHistory->formatted_answers = [];
|
|
}
|
|
|
|
if (!is_null($taskHistory->entry_date) && !is_null($taskHistory->departure_date)) {
|
|
// Converte para instâncias de Carbon
|
|
$entryDate = \Carbon\Carbon::parse($taskHistory->entry_date);
|
|
$departureDate = \Carbon\Carbon::parse($taskHistory->departure_date);
|
|
|
|
// Calcula a diferença em minutos, horas e dias
|
|
$diffInMinutes = $entryDate->diffInMinutes($departureDate);
|
|
$diffInHours = $entryDate->diffInHours($departureDate);
|
|
$diffInDays = $entryDate->diffInDays($departureDate);
|
|
|
|
// Se a diferença for menos de uma hora
|
|
if ($diffInMinutes < 60) {
|
|
$taskHistory->runtime = $diffInMinutes . ' minutos';
|
|
}
|
|
// Se a diferença for menos de 24 horas mas mais que uma hora
|
|
else if ($diffInHours < 24) {
|
|
$taskHistory->runtime = $diffInHours . ' horas';
|
|
}
|
|
// Se for mais de 24 horas
|
|
else {
|
|
// Calcula horas restantes após contar os dias
|
|
$remainingHours = $diffInHours % 24;
|
|
$taskHistory->runtime = $diffInDays . ' dias ' . $remainingHours . ' horas';
|
|
}
|
|
} else {
|
|
$taskHistory->runtime = 'N/A'; // Ou qualquer valor padrão que você prefira
|
|
}
|
|
}
|
|
|
|
|
|
// Nao esta a receber itens
|
|
|
|
// dd($allWorkstationsTaskAnswers);
|
|
// Agora cada objeto dentro de $tasksAssociatedWithAmbit tem uma propriedade 'elemental_task_description'.
|
|
|
|
//buscar Tarfas e tempo de execussao pelo control, assim como suas respostas.
|
|
// dd($receiveAmbit);
|
|
|
|
|
|
return view('projectsClients.showAmbitDetailProjectHistory', compact('detailsProject', 'receiveAmbit', 'receiveAllTasksHistiory', 'detalsEquipment'));
|
|
|
|
}
|
|
|
|
// public function showAllClientsForProjectReportsTable()
|
|
// {
|
|
|
|
// // Primeiro, buscamos todos os clientes com type_users = 3
|
|
// $allClients = User::where('type_users', 3)->get();
|
|
|
|
// // Inicializa um array para manter a contagem de projetos por cliente
|
|
// $clientProjectCounts = [];
|
|
|
|
// foreach ($allClients as $client) {
|
|
// // Para cada cliente, obtemos os plant_ids associados
|
|
// $plantIds = Plant::where('user_id', $client->user_id)->pluck('plant_id');
|
|
|
|
// // Agora, para cada plant_id, contamos os CompanyProjects associados com datas de início e fim não nulas
|
|
// $projectCount = CompanyProject::whereIn('plant_id', $plantIds)
|
|
// ->whereNotNull('date_started')
|
|
// ->whereNotNull('end_date')
|
|
// ->count();
|
|
|
|
// // Armazenamos a contagem no array com o user_id como chave
|
|
// $clientProjectCounts[$client->user_id] = $projectCount;
|
|
// }
|
|
|
|
|
|
// return DataTables()
|
|
// ->addColumn('action', function ($detailsClient){
|
|
// $actionBtn = '<a title="Detalhes do equipamento" href="' . route('reportingDataClient', ['clientID' => $detailsClient->user_id]) . '"><i class="fa-solid fa-eye text-primary"></i></a>';
|
|
// return $actionBtn;
|
|
// });
|
|
|
|
// }
|
|
|
|
|
|
|
|
public function showAllClientsForProjectReportsTable()
|
|
{
|
|
// Buscamos todos os clientes com type_users = 3
|
|
$allClientsQuery = User::where('type_users', 3);
|
|
|
|
// Retornamos o objeto DataTables
|
|
return DataTables::of($allClientsQuery)
|
|
|
|
->addColumn('client', function ($client) {
|
|
// Aqui você pode retornar o ID do cliente ou algum outro identificador
|
|
return $client->user_name;
|
|
})
|
|
->addColumn('amount_of_projects_completed', function ($client) {
|
|
// Para cada cliente, obtemos os plant_ids associados
|
|
$plantIds = Plant::where('user_id', $client->user_id)->pluck('plant_id');
|
|
|
|
// Contamos os CompanyProjects associados com datas de início e fim não nulas
|
|
$projectCount = CompanyProject::whereIn('plant_id', $plantIds)
|
|
->whereNotNull('date_started')
|
|
->whereNotNull('end_date')
|
|
->count();
|
|
|
|
// Retornamos a contagem
|
|
return $projectCount;
|
|
})
|
|
->addColumn('action', function ($client) {
|
|
// Geramos o botão de ação
|
|
$actionBtn = '<a title="Detalhes do equipamento" href="' . route('reportingDataClient', ['clientID' => $client->user_id]) . '"><i class="fa-solid fa-eye text-primary"></i></a>';
|
|
return $actionBtn;
|
|
})
|
|
->rawColumns(['action']) // Isso permite que o HTML seja renderizado
|
|
->make(true);
|
|
}
|
|
|
|
public function showAllClientsForProjectReports()
|
|
{
|
|
return view('userClient.showAllClientsForProjectReports');
|
|
}
|
|
|
|
public function testRelatorio()
|
|
{
|
|
// Obter o caminho da imagem do usuário ou uma imagem padrão
|
|
$userLogoPath = Auth::user()->user_logo ? public_path('user_logos/' . Auth::user()->user_logo) : public_path('user_logos/logoISPT4.0.jpg');
|
|
|
|
$pdf = PDF::loadView('testeRelatorio', ['userLogoPath' => $userLogoPath])->setPaper('a4', 'landscape');
|
|
|
|
|
|
return $pdf->stream('relatorio_teste.pdf');
|
|
// return view('testeRelatorio',compact('userLogoPath'));
|
|
}
|
|
|
|
|
|
public function receiveUnitsManageAssets($receivePlantClientRelated)
|
|
{
|
|
|
|
$UnitsData = Unit::where('plant_id', $receivePlantClientRelated)->get();
|
|
|
|
$formattedData = $UnitsData->map(function ($item) {
|
|
return [
|
|
'id' => $item->unit_id,
|
|
'name' => $item->unit_name
|
|
];
|
|
});
|
|
|
|
return response()->json($formattedData);
|
|
}
|
|
|
|
public function receivePlants($receiveAllClients)
|
|
{
|
|
$PlantData = Plant::where('user_id', $receiveAllClients)->get();
|
|
// Criando um array para armazenar os dados formatados
|
|
$formattedData = $PlantData->map(function ($item) {
|
|
return [
|
|
'id' => $item->plant_id,
|
|
'name' => $item->plant_name
|
|
];
|
|
});
|
|
// Retorna os dados em formato JSON
|
|
return response()->json($formattedData);
|
|
}
|
|
|
|
|
|
//Funcao que recebe a Acoes do dataTables das obrar em Planeamento.
|
|
public function projectDetails_11($projectID, $equipmentID)
|
|
{
|
|
$detailsProject = CompanyProject::find($projectID);
|
|
|
|
$dataEquipment = Equipment::find($equipmentID);
|
|
|
|
$detailsEquipmentWorkHistory = EquipmentWorkHistory::where('equipment_id', $dataEquipment->equipment_id)->first();
|
|
|
|
$receiveEquipmentWorkHistorys = EquipmentWorkHistory::where('equipment_id', $equipmentID)
|
|
->where('company_projects_id', $projectID)
|
|
->first();
|
|
|
|
$attributes = SpecificAttributesEquipmentType::where('equipment_id', $equipmentID)->get(); // recebe todos os atributos espesificos do equipamento
|
|
|
|
// $DetailsTasks = OrderEquipmentTasks::where('equipmentWorkHistorys_id', $receiveEquipmentWorkHistorys->equipmentWorkHistorys_id)->get(); // Todas as tarefas que o equipamento vai realizar :
|
|
|
|
// Obtém todas as tarefas associadas ao histórico do equipamento
|
|
$DetailsTasks = OrderEquipmentTasks::where('equipmentWorkHistorys_id', $receiveEquipmentWorkHistorys->equipmentWorkHistorys_id)
|
|
->whereNotNull('elemental_tasks_id')
|
|
->with([
|
|
'elementalTask' => function ($query) {
|
|
$query->whereNotNull('company_projects_id');
|
|
}
|
|
])
|
|
->get();
|
|
|
|
// Filtra para manter apenas os registros que realmente têm uma tarefa elemental associada com company_projects_id não nulo
|
|
$filteredTasks = $DetailsTasks->filter(function ($task) {
|
|
return !is_null($task->elementalTask) && !is_null($task->elementalTask->company_projects_id);
|
|
});
|
|
|
|
// Agora, vamos buscar os detalhes das tarefas elementais correspondentes
|
|
$elementalTasksDetails = ElementalTasks::whereIn('elemental_tasks_id', $filteredTasks->pluck('elemental_tasks_id'))
|
|
->whereNotNull('company_projects_id')
|
|
->get()
|
|
->keyBy('elemental_tasks_id'); // Keying by elemental_tasks_id para fácil acesso
|
|
|
|
|
|
// $filteredTasks = $filteredTasks->map(function ($task) use ($elementalTasksDetails) {
|
|
// // Verifica se o detalhe da tarefa elemental existe na coleção $elementalTasksDetails, com base no elemental_tasks_id
|
|
// if (isset ($elementalTasksDetails[$task->elemental_tasks_id])) {
|
|
// $elementalTaskDetail = $elementalTasksDetails[$task->elemental_tasks_id];
|
|
|
|
// // Adiciona novos atributos ao item da coleção $task com os detalhes da tarefa elemental
|
|
// $task->elemental_tasks_code = $elementalTaskDetail->elemental_tasks_code;
|
|
// $task->elemental_tasks_description = $elementalTaskDetail->elemental_tasks_description;
|
|
// $task->further_tasks_description = $elementalTaskDetail->further_tasks_description; // Ajuste este campo conforme sua existência e necessidade
|
|
// }
|
|
|
|
// // Retorna o item modificado para a nova coleção
|
|
// return $task;
|
|
// });
|
|
|
|
// $filteredTasks = $filteredTasks->map(function ($task) use ($DetailsTasks) {
|
|
// // Calcula o execution_order da tarefa anterior
|
|
// $executionOrderBefore = $task->execution_order - 1;
|
|
|
|
// // Busca a tarefa anterior com base no execution_order calculado
|
|
// $taskBefore = $DetailsTasks->first(function ($item) use ($executionOrderBefore) {
|
|
// return $item->execution_order == $executionOrderBefore;
|
|
// });
|
|
|
|
// // Se encontrou a tarefa anterior, adiciona seu elemental_tasks_id ao item atual
|
|
// if ($taskBefore) {
|
|
// $task->taskIDBeforeExecutionOrder = $taskBefore->elemental_tasks_id;
|
|
// } else {
|
|
// // Se não encontrar a tarefa anterior, pode definir como null ou outro valor padrão
|
|
// $task->taskIDBeforeExecutionOrder = null;
|
|
// }
|
|
|
|
// return $task;
|
|
// });
|
|
|
|
$filteredTasks = $filteredTasks->map(function ($task) use ($elementalTasksDetails, $DetailsTasks) {
|
|
// Primeiro bloco: Adiciona detalhes da tarefa elemental
|
|
if (isset ($elementalTasksDetails[$task->elemental_tasks_id])) {
|
|
$elementalTaskDetail = $elementalTasksDetails[$task->elemental_tasks_id];
|
|
$task->elemental_tasks_code = $elementalTaskDetail->elemental_tasks_code;
|
|
$task->elemental_tasks_description = $elementalTaskDetail->elemental_tasks_description;
|
|
$task->further_tasks_description = $elementalTaskDetail->further_tasks_description; // Ajuste conforme necessário
|
|
}
|
|
|
|
// Segundo bloco: Adiciona o ID da tarefa anterior
|
|
$executionOrderBefore = $task->execution_order - 1;
|
|
$taskBefore = $DetailsTasks->first(function ($item) use ($executionOrderBefore) {
|
|
return $item->execution_order == $executionOrderBefore;
|
|
});
|
|
|
|
if ($taskBefore) {
|
|
$task->taskIDBeforeExecutionOrder = $taskBefore->elemental_tasks_id;
|
|
} else {
|
|
$task->taskIDBeforeExecutionOrder = null;
|
|
}
|
|
|
|
// Retorna o item modificado para a nova coleção
|
|
return $task;
|
|
});
|
|
|
|
|
|
// Para buscar a tarefa com execution_order = 3
|
|
$taskBeforeExecutionOrder = OrderEquipmentTasks::where('equipmentWorkHistorys_id', $receiveEquipmentWorkHistorys->equipmentWorkHistorys_id)
|
|
->where('execution_order', 3)
|
|
->whereNotNull('elemental_tasks_id')
|
|
->first();
|
|
|
|
if ($taskBeforeExecutionOrder) {
|
|
$elementalTaskBefore = ElementalTasks::where('elemental_tasks_id', $taskBeforeExecutionOrder->elemental_tasks_id)
|
|
->whereNotNull('company_projects_id')
|
|
->first();
|
|
}
|
|
|
|
|
|
// $OrdemTasks = $DetailsTasks->pluck('elemental_tasks_id')->all(); // Array de IDs
|
|
$OrdemTasks = $DetailsTasks->pluck('execution_order', 'elemental_tasks_id')->all();
|
|
|
|
// Ajuste para definir 'on' para cada tarefa
|
|
$OrdemTasks = $DetailsTasks->mapWithKeys(function ($task) {
|
|
return [$task->elemental_tasks_id => 'on'];
|
|
})->all();
|
|
|
|
$specificAttributes = SpecificAttributesEquipmentType::where('equipment_id', $dataEquipment->equipment_id)->get();
|
|
|
|
$specificAttributesArray = [];
|
|
|
|
foreach ($specificAttributes as $attribute) {
|
|
$specificAttributesArray[$attribute->general_attributes_equipment_id] = $attribute->specific_attributes_value;
|
|
}
|
|
|
|
return view('projectsClients.articulated_2_ShowEquipment', compact('detailsProject', 'dataEquipment', 'filteredTasks', 'OrdemTasks', 'DetailsTasks', 'detailsEquipmentWorkHistory', 'specificAttributesArray'));
|
|
}
|
|
|
|
//Funcao que recebe a Acoes do dataTables do portifolio.
|
|
public function articulated_22($equipmentID)
|
|
{
|
|
//Nao esta recebendo os selects
|
|
|
|
|
|
// $dataEquipment = Equipment::find($equipmentID);
|
|
// $detailsEquipmentWorkHistory = EquipmentWorkHistory::where('equipment_id',$equipmentID)->first();
|
|
// $attributes = SpecificAttributesEquipmentType::where('equipment_id',$equipmentID)->get(); // recebe todos os atributos espesificos do equipamento
|
|
// $OrdemTasks = OrderEquipmentTasks::where('equipmentWorkHistorys_id', $detailsEquipmentWorkHistory->equipmentWorkHistorys_id)->get(); // Todas as tarefas que o equipamento vai realizar :
|
|
// $OrdemTasksIds = $OrdemTasks->pluck('elemental_tasks_id')->all(); // Array de IDs
|
|
|
|
// $receiveAlldetailsEquipmentWorkHistory = EquipmentWorkHistory::where('equipment_id',$equipmentID)->get();
|
|
|
|
$dataEquipment = Equipment::find($equipmentID);
|
|
|
|
|
|
$receiveAlldetailsEquipmentWorkHistory = EquipmentWorkHistory::with('equipmentAssociationAmbit')
|
|
->where('equipment_id', $equipmentID)
|
|
->get();
|
|
|
|
foreach ($receiveAlldetailsEquipmentWorkHistory as $equipmentWorkHistory) {
|
|
// Verifica se a relação equipmentAssociationAmbit existe
|
|
if ($equipmentWorkHistory->equipmentAssociationAmbit) {
|
|
// Adiciona o ambits_id diretamente ao objeto EquipmentWorkHistory
|
|
$equipmentWorkHistory->ambitDetals = $equipmentWorkHistory->equipmentAssociationAmbit->ambitsEquipment->ambits_description;
|
|
}
|
|
if ($equipmentWorkHistory->companyProject) {
|
|
$equipmentWorkHistory->nameCompanyProject = $equipmentWorkHistory->companyProject->company_project_description;
|
|
$equipmentWorkHistory->date_started = $equipmentWorkHistory->companyProject->date_started;
|
|
}
|
|
}
|
|
|
|
$specificAttributes = SpecificAttributesEquipmentType::where('equipment_id', $dataEquipment->equipment_id)->get();
|
|
|
|
$specificAttributesArray = [];
|
|
|
|
foreach ($specificAttributes as $attribute) {
|
|
$specificAttributesArray[$attribute->general_attributes_equipment_id] = $attribute->specific_attributes_value;
|
|
}
|
|
|
|
return view('projectsClients.testRoute', compact('dataEquipment', 'receiveAlldetailsEquipmentWorkHistory', 'specificAttributesArray'));
|
|
|
|
}
|
|
|
|
|
|
public function getEquipmentDetails($receiveListEquipmentId)
|
|
{
|
|
$ids = explode(',', $receiveListEquipmentId);
|
|
|
|
$equipments = Equipment::whereIn('equipment_id', $ids)->get();
|
|
|
|
// Pegar os unique "equipment_type_id"s
|
|
$equipmentTypeIds = $equipments->pluck('equipment_type_id')->unique();
|
|
|
|
// Obter todos os "AmbitsEquipment" para esses "equipment_type_id"s
|
|
$ambitsEquipments = AmbitsEquipment::whereIn('equipment_type_id', $equipmentTypeIds)->get();
|
|
|
|
// Mapear os "AmbitsEquipment" de volta aos equipamentos correspondentes
|
|
foreach ($equipments as $equipment) {
|
|
$equipment->ambits = $ambitsEquipments->where('equipment_type_id', $equipment->equipment_type_id);
|
|
}
|
|
return response()->json($equipments);
|
|
}
|
|
|
|
public function receiveAllInstallationEquipment(Request $request)
|
|
{
|
|
$projectId = $request->get('receiveNumberProject');
|
|
|
|
$receveProject = CompanyProject::find($projectId);
|
|
$receveEquipments = Equipment::whereHas('unit.plant', function ($query) use ($receveProject) {
|
|
$query->where('plants.plant_id', '=', $receveProject->plant_id);
|
|
})
|
|
|
|
->where('company_projects_id', null) // Adiciona a condição aqui
|
|
->with(['equipmentType', 'unit'])
|
|
// ->with(['equipmentType', 'unit', 'equipmentAssociationAmbit.ambitsEquipment'])
|
|
->get();
|
|
|
|
return DataTables::of($receveEquipments)
|
|
->addColumn('equipment_type', function ($row) {
|
|
return $row->equipmentType->equipment_type_name;
|
|
})
|
|
->addColumn('unit', function ($row) {
|
|
return $row->unit->unit_name;
|
|
})
|
|
->toJson();
|
|
}
|
|
|
|
|
|
public function HomePage()
|
|
{
|
|
$CompanyProject = CompanyProject::all();
|
|
|
|
return view('Admin/index')
|
|
// return view('codePronto');
|
|
->with("CompanyProject", $CompanyProject);
|
|
}
|
|
|
|
public function ManageAssets()
|
|
{
|
|
|
|
$units = DB::table('plants')
|
|
->join('units', 'plants.plant_id', '=', 'units.plant_id')
|
|
->join('users', 'plants.user_id', '=', 'users.user_id')
|
|
->select('plants.*', 'units.unit_name', 'users.user_name as user_name')
|
|
->get();
|
|
|
|
$equipments = Equipment::all();
|
|
|
|
// $equipaments = DB::table('equipaments')
|
|
// ->join('factories','equipaments.factory_id', '=', 'factories.factories_id')
|
|
// ->join('equipament_types', 'equipaments.equipament_type_id', '=' , 'equipament_types.equipament_type_id')
|
|
// ->select('equipaments.*', 'factories.factories_name', 'equipament_types.equipment_type_name')
|
|
// ->get();
|
|
|
|
$allEquipmentType = EquipmentType::all();
|
|
|
|
$allClients = User::where('type_users', 3)->get();
|
|
|
|
return view('Admin/DataManagement/manageassets', compact('units', 'equipments', 'allEquipmentType', 'allClients'));
|
|
}
|
|
|
|
public function showUnit($id)
|
|
{
|
|
|
|
$equipaments = Equipment::where('equipment_id', $id)->firstOrFail();
|
|
return view('Admin/DataManagement/showEquipament', compact('equipaments'));
|
|
}
|
|
|
|
|
|
|
|
|
|
|
|
public function receiveEquipmentsProject($receiveNumberProject)
|
|
{
|
|
// Recebe os dados vindos da funcao 'data' criada na view
|
|
$equipment_type_id = request('equipment_type_id');
|
|
|
|
$ambits_id = request('ambits_id');
|
|
|
|
// Caso 'equipment_type_id' seja '#', mostra todos os equipamentos
|
|
if ($equipment_type_id == '#') {
|
|
$model = Equipment::query()
|
|
->where('company_projects_id', $receiveNumberProject)
|
|
->with(['equipmentType', 'unit', 'equipmentAssociationAmbit.ambitsEquipment']);
|
|
}
|
|
// Caso 'equipment_type_id' não seja '#', filtra os equipamentos por tipo e Âmbito (caso 'ambits_id' não seja '#')
|
|
else {
|
|
$equipment_type_id = intval($equipment_type_id);
|
|
$model = Equipment::where('equipments.equipment_type_id', $equipment_type_id)
|
|
->where('company_projects_id', $receiveNumberProject)
|
|
->join('equipment_association_ambits', 'equipments.equipment_id', '=', 'equipment_association_ambits.equipment_id')
|
|
->with(['equipmentType', 'unit', 'equipmentAssociationAmbit.ambitsEquipment']);
|
|
|
|
if ($ambits_id != '#') {
|
|
$ambits_id = intval($ambits_id);
|
|
$model->where('equipment_association_ambits.ambits_id', $ambits_id)
|
|
->where('company_projects_id', $receiveNumberProject);
|
|
}
|
|
}
|
|
return DataTables::of($model)
|
|
->addColumn('equipment_type', function ($row) {
|
|
return $row->equipmentType->equipment_type_name;
|
|
})
|
|
->addColumn('Unit', function ($row) {
|
|
return $row->unit->unit_name;
|
|
})
|
|
->addColumn('Ambits', function ($row) {
|
|
return $row->equipmentAssociationAmbit->ambitsEquipment->ambits_description;
|
|
})
|
|
// Este 2 em especial, tem a condicao se a tarefa elementar estiver a null ele deve pegar a valor do campo ao lado ou seja da further task.
|
|
->addColumn('order_tasks', function ($row) {
|
|
return $row->orderEquipmentTasks->sortBy('execution_order')->map(function ($task) {
|
|
// Se elementalTask não for null, retorna elemental_tasks_code
|
|
if (!is_null($task->elementalTask)) {
|
|
return $task->elementalTask->elemental_tasks_code;
|
|
}
|
|
// Caso contrário, retorna further_tasks_name
|
|
return $task->furtherTasks->further_tasks_name;
|
|
})->implode(' ||');
|
|
})
|
|
->addColumn('current_task', function ($row) {
|
|
return $row->controlEquipmentWorkstation->map(function ($task) {
|
|
// Se elementalTask não for null, retorna elemental_tasks_code
|
|
if (!is_null($task->elementalTask)) {
|
|
return $task->elementalTask->elemental_tasks_code;
|
|
}
|
|
// Caso contrário, retorna further_tasks_name
|
|
return $task->furtherTasks->further_tasks_name;
|
|
})->implode(' ||');
|
|
})
|
|
|
|
|
|
|
|
->addColumn('Inspec', function ($row) {
|
|
return $row->hasInspectionYes() ? 'Sim' : 'Nao';
|
|
})
|
|
->toJson();
|
|
}
|
|
|
|
public function receiveAllEquipments()
|
|
{
|
|
$model = Equipment::all();
|
|
// ->with(['equipmentType', 'unit']);
|
|
|
|
|
|
return DataTables::of($model)
|
|
// ->addColumn('equipment_type', function ($row) {
|
|
// return $row->equipmentType->equipment_type_name;
|
|
// })
|
|
// ->addColumn('Unit', function ($row) {
|
|
// return $row->unit->unit_name;
|
|
// })
|
|
->toJson();
|
|
}
|
|
|
|
public function receiveWorkstationProject($receiveNumberProject)
|
|
{
|
|
$model = ConstructionWorkstation::where('company_projects_id', $receiveNumberProject)->with('workstationsAssociationTasks');
|
|
|
|
// Se ao varificar na tabela 'workstationsAssociationTasks' a coluna elementalTask estiver a null, significa que e uma further task, sendo assim ele busca o campo ao lado.
|
|
return DataTables::of($model)
|
|
->addColumn('workstations_Association_Tasks', function ($row) {
|
|
return $row->workstationsAssociationTasks->map(function ($task) {
|
|
// Se elementalTask não for null, retorna elemental_tasks_code
|
|
if (!is_null($task->elementalTask)) {
|
|
return $task->elementalTask->elemental_tasks_code;
|
|
}
|
|
// Caso contrário, retorna further_tasks_name
|
|
return $task->furtherTask->further_tasks_name;
|
|
})->implode(' ||');
|
|
})
|
|
->toJson();
|
|
}
|
|
}
|