500 lines
21 KiB
PHP
Executable File
500 lines
21 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 showAmbitDetailsProjectHistory($projectID, $equipmentID)
|
|
{
|
|
$detailsProject = CompanyProject::where('company_projects_id', $projectID)->first();
|
|
|
|
$detalsEquipmentWorkProject = EquipmentWorkHistory::where('equipment_id', $equipmentID)
|
|
->where('company_projects_id', $projectID)->first();
|
|
|
|
$detalsEquipment = Equipment::where('equipment_id',$equipmentID)->first();
|
|
|
|
$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();
|
|
|
|
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)
|
|
{
|
|
|
|
$dataEquipment = Equipment::find($equipmentID);
|
|
|
|
$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
|
|
$OrdemTasks = OrderEquipmentTasks::where('equipmentWorkHistorys_id', $receiveEquipmentWorkHistorys->equipmentWorkHistorys_id)->get(); // Todas as tarefas que o equipamento vai realizar :
|
|
$OrdemTasksIds = $OrdemTasks->pluck('elemental_tasks_id')->all(); // Array de IDs
|
|
|
|
return view('projectsClients.articulated_2_ShowEquipment', compact('dataEquipment', 'OrdemTasks', 'OrdemTasksIds'));
|
|
}
|
|
|
|
|
|
//Funcao que recebe a Acoes do dataTables do portifolio.
|
|
public function articulated_22($equipmentID)
|
|
{
|
|
|
|
// $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;
|
|
}
|
|
}
|
|
|
|
return view('projectsClients.testRoute', compact('dataEquipment', 'receiveAlldetailsEquipmentWorkHistory'));
|
|
|
|
}
|
|
|
|
|
|
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();
|
|
}
|
|
}
|