934 lines
41 KiB
PHP
Executable File
934 lines
41 KiB
PHP
Executable File
<?php
|
|
|
|
namespace App\Http\Controllers;
|
|
|
|
use App\Models\AmbitsEquipment;
|
|
use App\Models\Company;
|
|
use App\Models\ControlEquipmentWorkstation;
|
|
use App\Models\ElementalTasks;
|
|
use App\Models\EquipmentAssociationAmbit;
|
|
use App\Models\EquipmentComment;
|
|
use App\Models\EquipmentWorkHistory;
|
|
use App\Models\ReceiveImagesControlEquipmentWorkstation;
|
|
use App\Models\TasksAssociationAmbits;
|
|
use App\Models\Unit;
|
|
use App\Models\workstationsTaskAnswers;
|
|
use Illuminate\Http\Request;
|
|
use Illuminate\Support\Facades\DB;
|
|
use App\Services\PdfWrapper;
|
|
use Illuminate\Support\Facades\Storage;
|
|
|
|
|
|
|
|
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 createPDFforcompletedEquipment($equipmentId)
|
|
{
|
|
$detailsEquipmentWorkHistory = EquipmentWorkHistory::where('equipment_id', $equipmentId)->first();
|
|
$detailsEquipment = Equipment::where('equipment_id', $equipmentId)->first();
|
|
$receiveDetailsProject = CompanyProject::where('company_projects_id', $detailsEquipmentWorkHistory->company_projects_id)->first();
|
|
$receiveAmbit = EquipmentAssociationAmbit::where('equipmentWorkHistorys_id', $detailsEquipmentWorkHistory->equipmentWorkHistorys_id)->first();
|
|
|
|
// dd($receiveDetailsProject->plant->company->company_logo);
|
|
|
|
// Recebe apenas as tarefas já feitas
|
|
$completedTasksHistory = ControlEquipmentWorkstation::with('workstationsTaskAnswers', 'receiveImages')
|
|
->where('equipmentWorkHistorys_id', $detailsEquipmentWorkHistory->equipmentWorkHistorys_id)
|
|
->whereNotNull('entry_date')
|
|
->whereNotNull('departure_date')
|
|
->has('workstationsTaskAnswers')
|
|
->orderBy('elemental_tasks_id', 'asc')
|
|
->get();
|
|
|
|
|
|
// Cria uma coleção para armazenar todas as tarefas, concluídas e não concluídas
|
|
$receiveAllTasksHistiory = collect();
|
|
$taskImages = [];
|
|
|
|
foreach ($completedTasksHistory as $taskHistory) {
|
|
$taskHistory->cardTypeStyle = 'gray';
|
|
$taskHistory->typeStatusHistory = 'historic';
|
|
|
|
$workstationTaskAnswer = $taskHistory->workstationsTaskAnswers->first();
|
|
|
|
if ($workstationTaskAnswer && $workstationTaskAnswer->answer_json) {
|
|
$answersArray = json_decode($workstationTaskAnswer->answer_json, true);
|
|
$formattedAnswers = [];
|
|
foreach ($answersArray as $item) {
|
|
if (isset($item['question']) && isset($item['value'])) {
|
|
$formattedAnswers[$item['question']] = $item['value'];
|
|
}
|
|
}
|
|
$taskHistory->formatted_answers = $formattedAnswers;
|
|
} else {
|
|
$taskHistory->formatted_answers = [];
|
|
}
|
|
|
|
if ($taskHistory->receiveImages) {
|
|
$imagePaths = $taskHistory->receiveImages->image_paths;
|
|
$taskImages[$taskHistory->control_equipment_workstation_id] = is_array($imagePaths) ? $imagePaths : json_decode($imagePaths, true);
|
|
} else {
|
|
$taskImages[$taskHistory->control_equipment_workstation_id] = [];
|
|
}
|
|
|
|
$receiveAllTasksHistiory->push($taskHistory);
|
|
}
|
|
|
|
// Agrupa as tarefas concluídas por elemental_tasks_id e seleciona a mais recente por departure_date
|
|
$receiveAllTasksHistiory = $receiveAllTasksHistiory->groupBy(function ($item) {
|
|
return $item->elemental_tasks_id;
|
|
})->map(function ($group) {
|
|
return $group->sortByDesc('departure_date')->first();
|
|
});
|
|
|
|
|
|
// // Define os caminhos das logos
|
|
// $defaultLogoPath = '/img/ispt/4.0/Ispt4.0_Símbolo_Fundo_Azul-Marinho@2x-100.jpg';
|
|
|
|
// // Verifica se a logo do projeto está definida e não está vazia
|
|
// $projectLogoPath = !empty($receiveDetailsProject->plant->company->project_logo) ? $receiveDetailsProject->plant->company->project_logo : $defaultLogoPath;
|
|
|
|
// // Verifica se a logo da empresa está definida e não está vazia
|
|
// $companyLogoPath = !empty($receiveDetailsProject->plant->company->company_logo) ? $receiveDetailsProject->plant->company->company_logo : $defaultLogoPath;
|
|
|
|
|
|
// Define os caminhos das logos
|
|
$defaultLogoPath = '/img/ispt/4.0/Ispt4.0_Símbolo_Fundo_Azul-Marinho@2x-100.jpg';
|
|
|
|
// Verifica se a logo do projeto está definida e não está vazia
|
|
$projectLogoPath = !empty($receiveDetailsProject->plant->company->project_logo) ? $receiveDetailsProject->plant->company->project_logo : $defaultLogoPath;
|
|
|
|
// Verifica se a logo da empresa está definida e não está vazia
|
|
if (!empty($receiveDetailsProject->plant->company->company_logo)) {
|
|
$companyLogoPath = '/companies_logo/' . $receiveDetailsProject->plant->company->company_logo;
|
|
} else {
|
|
$companyLogoPath = $defaultLogoPath;
|
|
}
|
|
|
|
// Converte as imagens para base64 usando o serviço PdfWrapper
|
|
$pdfWrapper = new PdfWrapper();
|
|
|
|
// dd($receiveAllTasksHistiory);
|
|
|
|
// Gera e retorna o PDF
|
|
return $pdfWrapper
|
|
->loadView('projectsClients.pdf.testePdf', [
|
|
'tag' => $detailsEquipment->equipment_tag,
|
|
'numeroPanini' => $detailsEquipmentWorkHistory->ispt_number,
|
|
'nObra' => $receiveDetailsProject->project_company_name,
|
|
'ambito' => $receiveAmbit->ambitsEquipment->ambits_description,
|
|
'receiveAllTasksHistiory' => $receiveAllTasksHistiory,
|
|
'taskImages' => $taskImages,
|
|
'projectLogoPath' => $projectLogoPath,
|
|
'companyLogoPath' => $companyLogoPath
|
|
])
|
|
->stream('ispt40.pdf');
|
|
}
|
|
|
|
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'])
|
|
->where('order_project', $orderProjectID)
|
|
->get();
|
|
|
|
// Coletar todos as empresas em uma coleção separada
|
|
$companies = $receiveProjectsForThisOrder->map(function ($project) {
|
|
return $project->plant->company;
|
|
})->unique('company_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', 'companies', '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;
|
|
}
|
|
|
|
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_name';
|
|
|
|
// 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($equipmentStatus, $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;
|
|
|
|
$detailsEquipmentWorkProject = EquipmentWorkHistory::where('equipment_id', $equipmentID)
|
|
->where('company_projects_id', $projectID)->first();
|
|
|
|
//Recebe os comentarios do equipamento
|
|
$receiveComments = EquipmentComment::with(['user'])
|
|
->where('equipmentWorkHistorys_id', $detailsEquipmentWorkProject->equipmentWorkHistorys_id)
|
|
->where('company_projects_id', $detailsProject->company_projects_id)
|
|
->get()
|
|
->transform(function ($comment) {
|
|
// Adiciona uma nova propriedade ao objeto de comentário
|
|
$comment->type_users = $comment->user->type_users;
|
|
return $comment;
|
|
});
|
|
|
|
$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', $detailsEquipmentWorkProject->equipmentWorkHistorys_id)->get();
|
|
|
|
$receiveAmbit = EquipmentAssociationAmbit::where('equipmentWorkHistorys_id', $detailsEquipmentWorkProject->equipmentWorkHistorys_id)->first();
|
|
// $tasksAssociatedWithAmbit = TasksAssociationAmbits::where('ambits_equipment_id', $receiveAmbit->ambits_id)->get();
|
|
|
|
// Busca todas as tarefas do equipamento na ordem de execução
|
|
$receiveAllTasksEquipmentInHistory = OrderEquipmentTasks::where('equipmentWorkHistorys_id', $detailsEquipmentWorkProject->equipmentWorkHistorys_id)
|
|
->orderBy('execution_order', 'asc')
|
|
->get();
|
|
|
|
// Em seguida, obtenha todos os IDs de tarefas elementares de $receiveAllTasksEquipmentInHistory
|
|
$equipmentTasksIds = $receiveAllTasksEquipmentInHistory->pluck('elemental_tasks_id')->filter()->unique();
|
|
|
|
// Recebe apenas as tarefas já feitas
|
|
$completedTasksHistory = ControlEquipmentWorkstation::with('workstationsTaskAnswers')
|
|
->where('equipmentWorkHistorys_id', $detailsEquipmentWorkProject->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
|
|
->orderBy('elemental_tasks_id', 'asc')
|
|
->get();
|
|
|
|
|
|
// Cria uma coleção para armazenar todas as tarefas, concluídas e não concluídas
|
|
$receiveAllTasksHistiory = collect();
|
|
|
|
// Adiciona as tarefas concluídas à coleção principal
|
|
foreach ($completedTasksHistory as $taskHistory) {
|
|
$taskHistory->cardTypeStyle = 'gray'; // Adiciona o campo 'cardTypeStyle'
|
|
$taskHistory->typeStatusHistory = 'historic';
|
|
|
|
// 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 ($taskHistory->receiveImages) {
|
|
$imagePaths = $taskHistory->receiveImages->image_paths;
|
|
$taskHistory->image_paths = is_array($imagePaths) ? $imagePaths : json_decode($imagePaths, true);
|
|
} else {
|
|
$taskHistory->image_paths = [];
|
|
}
|
|
|
|
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
|
|
}
|
|
|
|
// Adiciona o taskHistory à coleção principal
|
|
$receiveAllTasksHistiory->push($taskHistory);
|
|
}
|
|
|
|
// Agrupa e ordena as tarefas concluídas por elemental_tasks_id e departure_date
|
|
$receiveAllTasksHistiory = $receiveAllTasksHistiory->groupBy(function ($item) {
|
|
return $item->elemental_tasks_id;
|
|
})->map(function ($group) {
|
|
$latest = $group->sortByDesc('departure_date')->first();
|
|
$latest->statusHistory = 'yes';
|
|
$history = $group->sortByDesc('departure_date')->slice(1)->map(function ($item) {
|
|
$item->statusHistory = 'no';
|
|
return $item;
|
|
});
|
|
|
|
return [
|
|
'latest' => $latest,
|
|
'history' => $history->values()
|
|
];
|
|
});
|
|
|
|
// Adiciona as tarefas não concluídas à coleção principal
|
|
$incompleteTasks = $equipmentTasksIds->diff($completedTasksHistory->pluck('elemental_tasks_id'));
|
|
|
|
foreach ($incompleteTasks as $taskId) {
|
|
// Busca os dados da tarefa elementar
|
|
$elementalTask = ElementalTasks::where('elemental_tasks_id', $taskId)->first();
|
|
|
|
// Adiciona à coleção principal usando o elemental_tasks_id como chave
|
|
$receiveAllTasksHistiory->put($taskId, [
|
|
'latest' => (object) [
|
|
'elemental_tasks_id' => $taskId,
|
|
'control_equipment_workstation_id' => 'N/A',
|
|
'cardType' => 'blue',
|
|
'cardTypeStyle' => 'blue',
|
|
'formatted_answers' => [],
|
|
'entry_date' => 'N/A',
|
|
'runtime' => 'N/A',
|
|
'statusHistory' => 'N/A',
|
|
'typeStatusHistory' => 'N/A',
|
|
'elementalTask' => (object) [
|
|
'elemental_tasks_code' => $elementalTask ? $elementalTask->elemental_tasks_code : null,
|
|
'elemental_tasks_description' => $elementalTask ? $elementalTask->elemental_tasks_description : null
|
|
]
|
|
],
|
|
'history' => collect() // Histórico vazio para tarefas não concluídas
|
|
]);
|
|
}
|
|
|
|
// dd($receiveAllTasksHistiory);
|
|
|
|
//recebe normalmente, porem os checkbox nao conseguem buscar valor, execepto o ultimo dado.
|
|
|
|
return view('projectsClients.showAmbitDetailProjectHistory', compact('receiveComments', 'equipmentStatus', 'detailsProject', 'receiveAmbit', 'receiveAllTasksHistiory', 'detalsEquipment', 'detailsEquipmentWorkProject'));
|
|
|
|
}
|
|
|
|
// 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);
|
|
|
|
$allClientsQuery = Company::all();
|
|
|
|
// Retornamos o objeto DataTables
|
|
return DataTables::of($allClientsQuery)
|
|
|
|
->addColumn('company', function ($client) {
|
|
// Aqui você pode retornar o ID do cliente ou algum outro identificador
|
|
return $client->company_name;
|
|
})
|
|
->addColumn('amount_of_projects_completed', function ($client) {
|
|
// Para cada cliente, obtemos os plant_ids associados
|
|
$plantIds = Plant::where('company_id', $client->company_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->company_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('company_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);
|
|
|
|
$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
|
|
//O resultado sera as tarefas complementares, pois apenas estas tarefas tem company_projects_id associados.
|
|
$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, $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();
|
|
}
|
|
|
|
// dd($taskBeforeExecutionOrder);
|
|
|
|
// $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;
|
|
}
|
|
//filteredTasks', 'OrdemTasks', 'DetailsTasks' campos vazios para ISV.
|
|
|
|
|
|
return view('projectsClients.articulated_2_ShowEquipment', compact('detailsProject', 'dataEquipment', 'filteredTasks', 'OrdemTasks', 'DetailsTasks', 'specificAttributesArray', 'receiveEquipmentWorkHistorys'));
|
|
}
|
|
|
|
//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('receiveDetailsProject');
|
|
|
|
$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('companies', 'plants.company_id', '=', 'companies.company_id')
|
|
->select('plants.*', 'units.unit_name', 'companies.company_name as company_name')
|
|
->get();
|
|
|
|
$equipments = Equipment::all();
|
|
|
|
$allEquipmentType = EquipmentType::all();
|
|
|
|
$allClients = Company::all();
|
|
|
|
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();
|
|
}
|
|
|
|
public function changeEquipmentStatusOnProject(Request $request)
|
|
{
|
|
$receivedetailsUser = auth()->user();
|
|
|
|
$detailsEquipmentWorkHistory = EquipmentWorkHistory::where('equipment_id', $request->equipmentID)
|
|
->where('company_projects_id', $request->projectID)
|
|
->whereIn('equipment_status_project', [1, 4])
|
|
->first();
|
|
|
|
if ($request->choiseAdminForEquipment == 'approve') {
|
|
//Se for aprovado, libera o equipamento para relatorio.
|
|
$detailsEquipmentWorkHistory->equipment_status_project = 2;
|
|
} else {
|
|
// Se nao for aprovado, o equipamento fica para revisão
|
|
$detailsEquipmentWorkHistory->equipment_status_project = 4;
|
|
|
|
}
|
|
|
|
$detailsEquipmentWorkHistory->save();
|
|
|
|
//Sempre vai criar o comentario, a diferenca a se o equipamento tem status : 2 o comanterio vai para o relatorio,se nao vai para os comentarios da Ws.
|
|
$createCommet = new EquipmentComment;
|
|
$createCommet->equipmentWorkHistorys_id = $detailsEquipmentWorkHistory->equipmentWorkHistorys_id;
|
|
$createCommet->user_id = $receivedetailsUser->user_id;
|
|
$createCommet->company_projects_id = $detailsEquipmentWorkHistory->company_projects_id;
|
|
$createCommet->creation_date = now();
|
|
$createCommet->comment = $request->comment;
|
|
$createCommet->save();
|
|
|
|
if ($detailsEquipmentWorkHistory->equipment_status_project == 2) {
|
|
return redirect()->route('ExecutionProject', ['projectID' => $request->projectID])
|
|
->with('success', 'Equipamento aprovado, liberado para relatório.');
|
|
} else {
|
|
return redirect()->route('ExecutionProject', ['projectID' => $request->projectID])
|
|
->with('success', 'Equipamento Não aprovado, Enviado para revisar.');
|
|
}
|
|
|
|
}
|
|
|
|
public function createComment(Request $request)
|
|
{
|
|
|
|
auth()->user();
|
|
$newComment = new EquipmentComment;
|
|
$newComment->company_projects_id = $request->projectID;
|
|
$newComment->equipmentWorkHistorys_id = $request->equipmentID;
|
|
$newComment->user_id = auth()->user()->user_id;
|
|
$newComment->creation_date = now();
|
|
$newComment->comment = $request->comment;
|
|
$newComment->save();
|
|
|
|
return back();
|
|
}
|
|
|
|
public function equipmentTaskDetailsPdf()
|
|
{
|
|
return view('projectsClients.pdf.equipmentTaskDetailsPdf');
|
|
}
|
|
|
|
}
|