1362 lines
62 KiB
PHP
Executable File
1362 lines
62 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\HistoryOfEquipmentAmbitsInTheProject;
|
|
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 ZipArchive;
|
|
|
|
|
|
|
|
|
|
use Yajra\DataTables\Facades\DataTables;
|
|
use Carbon\Carbon;
|
|
|
|
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 DownloadAllPdfsWork(Request $request)
|
|
{
|
|
// Recuperar todos os equipamentos relacionados ao projeto
|
|
$detailsEquipments = Equipment::where("company_projects_id", $request->projectID)->get();
|
|
|
|
$receiveDetailsProject = CompanyProject::where('company_projects_id', $request->projectID)->first();
|
|
$files = [];
|
|
|
|
foreach ($detailsEquipments as $detailsEquipment) {
|
|
|
|
// Obter o histórico de trabalho do equipamento atual
|
|
$detailsEquipmentWorkHistory = EquipmentWorkHistory::where('equipment_id', $detailsEquipment->equipment_id)->first();
|
|
|
|
// Obter o âmbito associado ao histórico de trabalho do equipamento atual
|
|
$receiveAmbit = EquipmentAssociationAmbit::where('equipmentWorkHistorys_id', $detailsEquipmentWorkHistory->equipmentWorkHistorys_id)->first();
|
|
|
|
// Inicializa o array para armazenar os atributos específicos
|
|
$specificAttributesArray = [];
|
|
|
|
$receiveSpecificAttributes = SpecificAttributesEquipmentType::where('equipment_id', $detailsEquipment->equipment_id)->get();
|
|
$receiveAmbit = EquipmentAssociationAmbit::where('equipmentWorkHistorys_id', $detailsEquipmentWorkHistory->equipmentWorkHistorys_id)->first();
|
|
$receiveDetailsProject = CompanyProject::where('company_projects_id', $detailsEquipmentWorkHistory->company_projects_id)->first();
|
|
|
|
// Corre a coleção e preenche o array 'specificAttributesArray'
|
|
foreach ($receiveSpecificAttributes as $attribute) {
|
|
// Verifica se a relação com 'generalAttributesEquipment' existe para evitar erro
|
|
if (isset($attribute->generalAttributesEquipment)) {
|
|
$key = $attribute->general_attributes_equipment_id;
|
|
$description = $attribute->generalAttributesEquipment->general_attributes_equipment_description;
|
|
$value = $attribute->specific_attributes_value;
|
|
|
|
// Adiciona ao array temporário com a estrutura chave => [description, value]
|
|
$specificAttributesArray[$key] = [
|
|
'description' => $description,
|
|
'value' => $value
|
|
];
|
|
}
|
|
}
|
|
|
|
// Atribui o array de 'SpecificAttributes' ao modelo usando o método 'setAttribute'
|
|
$detailsEquipment->setAttribute('specificAttributes', $specificAttributesArray);
|
|
|
|
// 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();
|
|
|
|
|
|
// Verifica se a coleção tem registros
|
|
if ($completedTasksHistory->isNotEmpty()) {
|
|
// Obter a data mais antiga (primeira tarefa feita)
|
|
$oldestDate = $completedTasksHistory->min('departure_date');
|
|
|
|
// Obter a data mais recente (última tarefa feita)
|
|
$latestDate = $completedTasksHistory->max('departure_date');
|
|
|
|
// Formata as datas apenas para mostrar o dia
|
|
$startDate = \Carbon\Carbon::parse($oldestDate)->format('Y-m-d');
|
|
$endDate = \Carbon\Carbon::parse($latestDate)->format('Y-m-d');
|
|
|
|
} else {
|
|
|
|
// Caso não haja dados, defina datas nulas
|
|
$startDate = null;
|
|
$endDate = null;
|
|
}
|
|
|
|
// Apos receber todas as tarefas deve verificar qual o ambito atual e comparar em qual ambito foram feitas as tarefas, ai sim verificar oque foi feito no Ambito antigo e oque foi feito no atual.
|
|
// histórico de âmbitos por time_change_ambit do mais antigo ao mais recente
|
|
$receiveAmbitHistory = HistoryOfEquipmentAmbitsInTheProject::where('equipmentWorkHistorys_id', $detailsEquipmentWorkHistory->equipmentWorkHistorys_id)
|
|
->orderBy('time_change_ambit', 'desc')
|
|
->get();
|
|
|
|
|
|
// Identifica o último âmbito (o mais recente)
|
|
$latestAmbitHistory = $receiveAmbitHistory->last();
|
|
|
|
// Separa as tarefas do histórico por âmbitos diferentes
|
|
$tasksByAmbit = $completedTasksHistory->groupBy('history_of_equipment_ambits_id');
|
|
|
|
|
|
//coleção para armazenar todas as tarefas, concluídas e não concluídas
|
|
$receiveAllTasksHistiory = collect();
|
|
$taskImages = [];
|
|
|
|
// Contador para a ordem dos âmbitos
|
|
$ambitCounter = 1;
|
|
|
|
|
|
// Itera sobre cada âmbito anterior
|
|
foreach ($receiveAmbitHistory as $index => $ambitHistory) {
|
|
|
|
$ambitId = $ambitHistory->history_of_equipment_ambits_id;
|
|
|
|
|
|
// Verifica se há tarefas associadas a esse âmbito
|
|
if ($tasksByAmbit->has($ambitId)) {
|
|
$tasksForAmbit = $tasksByAmbit->get($ambitId);
|
|
|
|
// Loop para associar a ultima tarefa feita de acordo com o ambito relacionado com ela.
|
|
foreach ($tasksForAmbit as $taskHistory) {
|
|
if ($ambitId == $latestAmbitHistory->history_of_equipment_ambits_id) {
|
|
|
|
// Se a tarefa pertence ao último âmbito (mais recente)
|
|
$taskHistory->cardTypeStyle = 'gray';
|
|
$taskHistory->typeStatusHistory = 'historic';
|
|
} else {
|
|
|
|
// Se a tarefa pertence a âmbitos anteriores
|
|
$taskHistory->cardTypeStyle = 'blue';
|
|
$taskHistory->AmbitHistoryTimeChange = $ambitHistory->time_change_ambit;
|
|
$taskHistory->AmbitHistoryOrder = $ambitCounter; // Adiciona o contador
|
|
$taskHistory->typeStatusHistory = 'historic';
|
|
|
|
// Adiciona AmbitName dinamicamente
|
|
if ($ambitHistory->AmbitsEquipment) {
|
|
$taskHistory->AmbitName = $ambitHistory->AmbitsEquipment->ambits_description;
|
|
} else {
|
|
$taskHistory->AmbitName = 'N/A'; // Defina 'N/A' ou outro valor se não houver AmbitsEquipment
|
|
}
|
|
}
|
|
|
|
// Verifica se há um comentário associado e adiciona ao taskHistory
|
|
if ($taskHistory->taskEquipmentComment) {
|
|
$taskHistory->taskComment = $taskHistory->taskEquipmentComment->task_comment;
|
|
}
|
|
|
|
// else {
|
|
// $taskHistory->taskComment = 'N/A'; // Ou qualquer outro valor padrão caso não tenha comentário
|
|
// }
|
|
|
|
//recebe os dados do id da workstations_task_answers_id, control_equipment_workstation_id e as respostar : answer_json
|
|
$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);
|
|
}
|
|
}
|
|
|
|
// Incrementa o contador para o próximo âmbito
|
|
$ambitCounter++;
|
|
}
|
|
|
|
// 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- Simbolo ISPT_4.0
|
|
// $defaultLogoPath = '/img/ispt/4.0/Ispt4.0_Símbolo_Fundo_Azul-Marinho@2x-100.jpg';
|
|
|
|
$defaultLogoPath = '/img/ispt/4.0/Ispt4.0_Símbolo_Fundo_Azul-Marinho@2x-8.png';
|
|
|
|
$isptLogoPath = '/img/ispt/ispt.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;
|
|
}
|
|
|
|
// Cria uma coleção para armazenar os históricos de âmbitos
|
|
$ambitHistories = collect();
|
|
|
|
// Itera sobre a coleção original $receiveAllTasksHistiory
|
|
foreach ($receiveAllTasksHistiory as $taskHistory) {
|
|
|
|
// Verifica se os campos AmbitHistoryTimeChange e AmbitHistoryOrder estão presentes
|
|
if (isset($taskHistory->AmbitHistoryTimeChange) && isset($taskHistory->AmbitHistoryOrder)) {
|
|
|
|
// Extrai apenas a data da coluna AmbitHistoryTimeChange
|
|
$ambitDate = \Carbon\Carbon::parse($taskHistory->AmbitHistoryTimeChange)->format('Y-m-d');
|
|
|
|
// Cria uma nova entrada com os valores desejados
|
|
$ambitHistories->push([
|
|
'AmbitHistoryOrder' => $taskHistory->AmbitHistoryOrder,
|
|
'AmbitName' => isset($taskHistory->AmbitName) ? $taskHistory->AmbitName : 'N/A',
|
|
'AmbitHistoryTimeChange' => $ambitDate
|
|
]);
|
|
}
|
|
}
|
|
|
|
// Apos receber todas as tarefas deve verificar qual o ambito atual e comparar em qual ambito foram feitas as tarefas, ai sim verificar oque foi feito no Ambito antigo e oque foi feito no atual.
|
|
// histórico de âmbitos por time_change_ambit do mais antigo ao mais recente
|
|
$receiveAmbitHistory = HistoryOfEquipmentAmbitsInTheProject::where('equipmentWorkHistorys_id', $detailsEquipmentWorkHistory->equipmentWorkHistorys_id)
|
|
->orderBy('time_change_ambit', 'desc')
|
|
->get();
|
|
|
|
// Gerar o PDF individualmente usando a classe PdfWrapper
|
|
$pdfWrapper = new PdfWrapper();
|
|
|
|
$pdf = $pdfWrapper->loadView('projectsClients.pdf.testePdf', [
|
|
// 'detailsEquipment' => $detailsEquipment,
|
|
// 'detailsEquipmentWorkHistory' => $detailsEquipmentWorkHistory, // Incluindo a variável no PDF
|
|
// 'receiveDetailsProject' => $receiveDetailsProject,
|
|
// // ambitHistories
|
|
|
|
// 'ambito' => $receiveAmbit->ambitsEquipment->ambits_description ?? 'N/A', // Incluindo o âmbito associado
|
|
// // receiveAllTasksHistiory
|
|
// // taskImages
|
|
|
|
// 'projectLogoPath' => $projectLogoPath,
|
|
// 'companyLogoPath' => $companyLogoPath,
|
|
// 'isptLogoPath' => $isptLogoPath
|
|
|
|
|
|
'detailsEquipment' => $detailsEquipment,
|
|
'detailsEquipmentWorkHistory' => $detailsEquipmentWorkHistory,
|
|
'receiveDetailsProject' => $receiveDetailsProject,
|
|
'ambitHistories' => $ambitHistories,
|
|
'dataControlEquipment' => 'null',
|
|
|
|
'ambito' => $receiveAmbit->ambitsEquipment->ambits_description,
|
|
'recebeTasksForEquipment' => $receiveAllTasksHistiory,
|
|
'taskImages' => $taskImages,
|
|
'projectLogoPath' => $projectLogoPath,
|
|
'companyLogoPath' => $companyLogoPath,
|
|
'isptLogoPath' => $isptLogoPath,
|
|
|
|
'oldestDate' => $startDate, // Data mais antiga
|
|
'latestDate' => $endDate // Data mais recente
|
|
]);
|
|
|
|
// Definir o caminho para salvar o PDF
|
|
$filePath = 'temp/pdfs/Tag_' . $detailsEquipment->equipment_tag . '.pdf';
|
|
|
|
// Salvar o PDF no armazenamento local usando stream() com false para pegar o conteúdo
|
|
Storage::put($filePath, $pdf->stream('', ['Attachment' => false]));
|
|
|
|
// Adicionar o caminho do PDF na lista de arquivos
|
|
$files[] = storage_path('app/' . $filePath);
|
|
}
|
|
|
|
|
|
// Gerar o arquivo ZIP com todos os PDFs
|
|
$zipFilePath = $this->createZipWithPdfs($files, 'Relatorios Pdf Obra_' . $receiveDetailsProject->company_project_description . '.zip');
|
|
|
|
// Retornar o arquivo ZIP para download
|
|
return response()->download($zipFilePath)->deleteFileAfterSend(true);
|
|
}
|
|
|
|
|
|
// public function createZipWithPdfs($files, $zipFileName)
|
|
// {
|
|
// $zip = new ZipArchive;
|
|
// $zipDir = storage_path('app/temp/zips/');
|
|
// // Verifique se o diretório existe, caso contrário, crie-o
|
|
// if (!is_dir($zipDir)) {
|
|
// mkdir($zipDir, 0777, true); // Cria o diretório com permissões de escrita
|
|
// }
|
|
// $zipPath = $zipDir . $zipFileName;
|
|
// if ($zip->open($zipPath, ZipArchive::CREATE) === TRUE) {
|
|
// foreach ($files as $file) {
|
|
// $fileName = basename($file); // Pega o nome do arquivo
|
|
// $zip->addFile($file, $fileName); // Adiciona o arquivo PDF ao ZIP
|
|
// }
|
|
// $zip->close();
|
|
// } else {
|
|
// throw new \Exception("Não foi possível criar o arquivo ZIP.");
|
|
// }
|
|
// return $zipPath; // Caminho para o ZIP gerado
|
|
// }
|
|
|
|
|
|
public function createZipWithPdfs($files, $zipFileName)
|
|
{
|
|
$zip = new ZipArchive;
|
|
|
|
// Definir o caminho do diretório para armazenar o ZIP temporário
|
|
$zipDir = storage_path('app/temp/zips/');
|
|
|
|
// Garantir que o diretório "temp/zips" exista ou crie-o com permissões adequadas
|
|
if (!Storage::exists('temp/zips')) {
|
|
Storage::makeDirectory('temp/zips', 0777, true);
|
|
}
|
|
|
|
// Definir o caminho completo para o arquivo ZIP
|
|
$zipPath = $zipDir . $zipFileName;
|
|
|
|
// Tentar abrir o arquivo ZIP, se falhar, lançar exceção
|
|
if ($zip->open($zipPath, ZipArchive::CREATE) === TRUE) {
|
|
foreach ($files as $file) {
|
|
// Pega o nome do arquivo
|
|
$fileName = basename($file);
|
|
// Adiciona o arquivo PDF ao ZIP
|
|
$zip->addFile($file, $fileName);
|
|
}
|
|
// Finaliza o ZIP
|
|
$zip->close();
|
|
} else {
|
|
throw new \Exception("Não foi possível criar o arquivo ZIP.");
|
|
}
|
|
|
|
// Retornar o caminho para o ZIP gerado
|
|
return $zipPath;
|
|
}
|
|
|
|
|
|
|
|
|
|
public function completedEquipmentInProject(Request $request)
|
|
{
|
|
|
|
//Busca a ultima ocorrencia ou seja o ultima dado criado para deste equipamento para a obra atual.
|
|
$equipmentHistoryDetails = EquipmentWorkHistory::where('equipment_id', $request->equipment_id)
|
|
->where('company_projects_id', $request->company_projects_id)
|
|
->orderBy('equipmentWorkHistorys_id', 'desc') // Correct method for descending order
|
|
->first();
|
|
|
|
//Atualiza para o equipamento ir para os concluidos, mesmo sem fazer as tarefas.
|
|
$equipmentHistoryDetails->equipment_status_project = 1;
|
|
$equipmentHistoryDetails->justification_for_finalization = $request->reason;
|
|
$equipmentHistoryDetails->save();
|
|
|
|
//Recebe todas as tarefas ja feitas neste equipamento
|
|
$receiveTaskOfControl = ControlEquipmentWorkstation::where('equipmentWorkHistorys_id', $equipmentHistoryDetails->equipmentWorkHistorys_id)
|
|
->whereNotNull('departure_date')
|
|
->where('status', '1')
|
|
->get();
|
|
|
|
//recebe todas as tarefas previamente associadas
|
|
$receiveAllTasksForEquipmentHistory = OrderEquipmentTasks::where('equipmentWorkHistorys_id', $equipmentHistoryDetails->equipmentWorkHistorys_id)->get();
|
|
|
|
|
|
// Colete todos os 'elemental_tasks_id' da variável $receiveTaskOfControl
|
|
$taskControlIds = $receiveTaskOfControl->pluck('elemental_tasks_id')->toArray();
|
|
|
|
// Filtre as tarefas em $receiveAllTasksForEquipmentHistory que NÃO estão em $taskControlIds
|
|
$tasksToDelete = $receiveAllTasksForEquipmentHistory->filter(function ($task) use ($taskControlIds) {
|
|
return !in_array($task->elemental_tasks_id, $taskControlIds);
|
|
});
|
|
|
|
// Deleta as tarefas não correspondentes
|
|
if ($tasksToDelete->isNotEmpty()) {
|
|
OrderEquipmentTasks::whereIn('id', $tasksToDelete->pluck('id'))->delete();
|
|
}
|
|
|
|
// Voltar home da Obra Em execução
|
|
return redirect()->route('ExecutionProject', ['projectID' => $equipmentHistoryDetails->company_projects_id])
|
|
->with('success', 'Equipamento ' . $equipmentHistoryDetails->equipment->equipment_tag . 'foi alterado para "Concluido"');
|
|
|
|
}
|
|
|
|
public function createPDFforcompletedEquipment($equipmentId)
|
|
{
|
|
//Busca os detalhes do equipamento
|
|
$detailsEquipmentWorkHistory = EquipmentWorkHistory::where('equipment_id', $equipmentId)->first();
|
|
|
|
//Busca os detalhes do equipamento
|
|
$detailsEquipment = Equipment::where('equipment_id', $equipmentId)->first();
|
|
|
|
// Inicializa o array para armazenar os atributos específicos
|
|
$specificAttributesArray = [];
|
|
// Atribui o array de 'SpecificAttributes' ao modelo usando o método 'setAttribute'
|
|
$detailsEquipment->setAttribute('specificAttributes', $specificAttributesArray);
|
|
|
|
// Dados do Projecto atual
|
|
$receiveDetailsProject = CompanyProject::where('company_projects_id', $detailsEquipmentWorkHistory->company_projects_id)->first();
|
|
|
|
$receiveAmbit = EquipmentAssociationAmbit::where('equipmentWorkHistorys_id', $detailsEquipmentWorkHistory->equipmentWorkHistorys_id)->first();
|
|
|
|
// Busca todas as tarefas do equipamento na ordem de execução - junta com as ordem de execussao das tarefas = completedTasksHistory
|
|
$receiveAllTasksEquipmentInHistory = OrderEquipmentTasks::where('equipmentWorkHistorys_id', $detailsEquipmentWorkHistory->equipmentWorkHistorys_id)
|
|
->orderBy('execution_order', 'asc')
|
|
->get();
|
|
|
|
// Recebe apenas as tarefas já feitas - collection
|
|
$completedTasksHistory = ControlEquipmentWorkstation::with('workstationsTaskAnswers')
|
|
->where('equipmentWorkHistorys_id', $detailsEquipmentWorkHistory->equipmentWorkHistorys_id)
|
|
->whereNotNull('entry_date')
|
|
->whereNotNull('departure_date')
|
|
->has('workstationsTaskAnswers') // Garante que haja pelo menos uma 'workstationsTaskAnswers' relacionada
|
|
->orderBy('elemental_tasks_id', 'asc')
|
|
->get();
|
|
|
|
// Verifica se a coleção tem registros
|
|
if ($completedTasksHistory->isNotEmpty()) {
|
|
// Obter a data mais antiga (primeira tarefa feita)
|
|
$oldestDate = $completedTasksHistory->min('departure_date');
|
|
|
|
// Obter a data mais recente (última tarefa feita)
|
|
$latestDate = $completedTasksHistory->max('departure_date');
|
|
|
|
// Formata as datas apenas para mostrar o dia
|
|
$startDate = \Carbon\Carbon::parse($oldestDate)->format('Y-m-d');
|
|
$endDate = \Carbon\Carbon::parse($latestDate)->format('Y-m-d');
|
|
|
|
} else {
|
|
|
|
// Caso não haja dados, defina datas nulas
|
|
$startDate = null;
|
|
$endDate = null;
|
|
}
|
|
|
|
|
|
foreach ($completedTasksHistory as $taskHistory) {
|
|
$taskHistory->cardTypeStyle = '#8CC084'; // Adiciona o campo 'cardTypeStyle'
|
|
// $taskHistory->typeStatusHistory = 'historic'; -> verificar onde seria mais necessario criar esse atributo de historico
|
|
|
|
// Verifica se há um comentário associado e adiciona ao taskHistory
|
|
if ($taskHistory->taskEquipmentComment) {
|
|
$taskHistory->taskComment = $taskHistory->taskEquipmentComment->task_comment;
|
|
}
|
|
|
|
// 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 = [];
|
|
}
|
|
|
|
// Calcula o tempo de execução se as datas de entrada e saída nao forem nulas
|
|
if (!is_null($taskHistory->entry_date) && !is_null($taskHistory->departure_date)) {
|
|
|
|
$entryDate = \Carbon\Carbon::parse($taskHistory->entry_date);
|
|
$departureDate = \Carbon\Carbon::parse($taskHistory->departure_date);
|
|
|
|
$diffInMinutes = $entryDate->diffInMinutes($departureDate);
|
|
$diffInHours = $entryDate->diffInHours($departureDate);
|
|
$diffInDays = $entryDate->diffInDays($departureDate);
|
|
|
|
if ($diffInMinutes < 60) {
|
|
$taskHistory->runtime = $diffInMinutes . ' minutos';
|
|
} elseif ($diffInHours < 24) {
|
|
$taskHistory->runtime = $diffInHours . ' horas';
|
|
} else {
|
|
$remainingHours = $diffInHours % 24;
|
|
$taskHistory->runtime = $diffInDays . ' dias ' . $remainingHours . ' horas';
|
|
}
|
|
} else {
|
|
$taskHistory->runtime = 'N/A';
|
|
}
|
|
}
|
|
|
|
|
|
|
|
// Define os caminhos das logos- Simbolo ISPT_4.0
|
|
$defaultLogoPath = '/img/ispt/4.0/Ispt4.0_Símbolo_Fundo_Azul-Marinho@2x-8.png';
|
|
|
|
$isptLogoPath = '/img/ispt/ispt.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;
|
|
}
|
|
// dd($completedTasksHistory);
|
|
|
|
//Precisamos receber o Tipo de equipamento e detalhes da Obra, alem do atributos especificos de acordo com o tipo de equipamento.
|
|
// Converte as imagens para base64 usando o serviço PdfWrapper
|
|
|
|
$pdfWrapper = new PdfWrapper();
|
|
|
|
// Gera e retorna o PDF
|
|
return $pdfWrapper
|
|
|
|
// ->setIncludePath('$PATH:/usr/bin')
|
|
->loadView('projectsClients.pdf.testePdf', [
|
|
|
|
'detailsEquipment' => $detailsEquipment,
|
|
'detailsEquipmentWorkHistory' => $detailsEquipmentWorkHistory,
|
|
'receiveDetailsProject' => $receiveDetailsProject,
|
|
// 'ambitHistories' => $ambitHistories,
|
|
|
|
'dataControlEquipment' => [
|
|
'typePageForViewElementalTasks' => 'pdf'
|
|
],
|
|
|
|
'ambito' => $receiveAmbit->ambitsEquipment->ambits_description,
|
|
'recebeTasksForEquipment' => $completedTasksHistory,
|
|
// 'taskImages' => $taskImages,
|
|
'taskImages' => '[]',
|
|
|
|
'projectLogoPath' => $projectLogoPath,
|
|
'companyLogoPath' => $companyLogoPath,
|
|
'isptLogoPath' => $isptLogoPath,
|
|
|
|
'oldestDate' => $startDate, // Data mais antiga
|
|
'latestDate' => $endDate // Data mais recente
|
|
])
|
|
|
|
->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)
|
|
{
|
|
// Dados do Projecto atual
|
|
$detailsProject = CompanyProject::where('company_projects_id', $projectID)->first();
|
|
|
|
//Detalhes do equipmento em relacao a obra atual
|
|
$detailsEquipmentWorkProject = EquipmentWorkHistory::where('equipment_id', $equipmentID)
|
|
->where('company_projects_id', $projectID)->first();
|
|
|
|
//Recebe os comentarios do equipamento, assim por ter ligacao com a Model 'User', para cada valor recebido no get(), consegue criar um novo atributo a collection $comment->type_user
|
|
$receiveComments = EquipmentComment::with(['user'])
|
|
->where('equipmentWorkHistorys_id', $detailsEquipmentWorkProject->equipmentWorkHistorys_id)
|
|
->where('company_projects_id', $detailsProject->company_projects_id)
|
|
->get()
|
|
|
|
//Talvez nao seja necessario isto, pois a model EquipmentComment, ja tem relacao com a 'User'
|
|
->transform(function ($comment) {
|
|
// Adiciona uma nova propriedade ao objeto de comentário
|
|
$comment->type_user = $comment->user->type_users;
|
|
return $comment;
|
|
});
|
|
|
|
//Recebe os dados padrao do Equipamento e o atribui uma nova coluna :typeOfPortfolioStructure , para indicar ser um dado de Historico.
|
|
$detalsEquipment = Equipment::where('equipment_id', $equipmentID)->first();
|
|
$detalsEquipment->typeOfPortfolioStructure = 'History';
|
|
|
|
//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();
|
|
// $tasksAssociatedWithAmbit = TasksAssociationAmbits::where('ambits_equipment_id', $receiveAmbit->ambits_id)->get();
|
|
|
|
$receiveAmbit = EquipmentAssociationAmbit::where('equipmentWorkHistorys_id', $detailsEquipmentWorkProject->equipmentWorkHistorys_id)->first();
|
|
|
|
// Busca todas as tarefas do equipamento na ordem de execução
|
|
$receiveAllTasksEquipmentInHistory = OrderEquipmentTasks::where('equipmentWorkHistorys_id', $detailsEquipmentWorkProject->equipmentWorkHistorys_id)
|
|
->orderBy('execution_order', 'asc')
|
|
->get();
|
|
|
|
// Recebe todos os IDs de tarefas elementares de $receiveAllTasksEquipmentInHistory em array
|
|
$equipmentTasksIds = $receiveAllTasksEquipmentInHistory->pluck('elemental_tasks_id')->filter()->unique();
|
|
|
|
// Recebe todas as tarefas concluídas relacionadas à Workstation, ordenadas por 'elemental_tasks_id' e 'departure_date'
|
|
$completedTasksHistory = ControlEquipmentWorkstation::with('workstationsTaskAnswers')
|
|
->where('equipmentWorkHistorys_id', $detailsEquipmentWorkProject->equipmentWorkHistorys_id)
|
|
->whereNotNull('entry_date')
|
|
->whereNotNull('departure_date')
|
|
->has('workstationsTaskAnswers')
|
|
->orderBy('elemental_tasks_id', 'asc')
|
|
->orderBy('departure_date', 'desc') // Ordena por data mais recente primeiro
|
|
->get()
|
|
->unique('elemental_tasks_id'); // Garante a última ocorrência para cada 'elemental_tasks_id'
|
|
|
|
|
|
// 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 = '#8CC084'; // Adiciona o campo 'cardTypeStyle'
|
|
// $taskHistory->typeStatusHistory = 'historic'; -> verificar onde seria mais necessario criar esse atributo de historico
|
|
|
|
// Verifica se há um comentário associado e adiciona ao taskHistory
|
|
if ($taskHistory->taskEquipmentComment) {
|
|
$taskHistory->taskComment = $taskHistory->taskEquipmentComment->task_comment;
|
|
}
|
|
|
|
// 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 = [];
|
|
}
|
|
|
|
// Calcula o tempo de execução se as datas de entrada e saída nao forem nulas
|
|
if (!is_null($taskHistory->entry_date) && !is_null($taskHistory->departure_date)) {
|
|
|
|
$entryDate = \Carbon\Carbon::parse($taskHistory->entry_date);
|
|
$departureDate = \Carbon\Carbon::parse($taskHistory->departure_date);
|
|
|
|
$diffInMinutes = $entryDate->diffInMinutes($departureDate);
|
|
$diffInHours = $entryDate->diffInHours($departureDate);
|
|
$diffInDays = $entryDate->diffInDays($departureDate);
|
|
|
|
if ($diffInMinutes < 60) {
|
|
$taskHistory->runtime = $diffInMinutes . ' minutos';
|
|
} elseif ($diffInHours < 24) {
|
|
$taskHistory->runtime = $diffInHours . ' horas';
|
|
} else {
|
|
$remainingHours = $diffInHours % 24;
|
|
$taskHistory->runtime = $diffInDays . ' dias ' . $remainingHours . ' horas';
|
|
}
|
|
} else {
|
|
$taskHistory->runtime = 'N/A';
|
|
}
|
|
|
|
// Define a estrutura baseada na propriedade statusAmbit para 'latest' e 'history'
|
|
$receiveAllTasksHistiory->push($taskHistory);
|
|
}
|
|
|
|
// Reorganiza a coleção por elemental_tasks_id, definindo a propriedade statusAmbit
|
|
$receiveAllTasksHistiory = $receiveAllTasksHistiory->groupBy('elemental_tasks_id')
|
|
->map(function ($group) {
|
|
return $group->map(function ($task) use ($group) {
|
|
// Marcar a tarefa mais recente como 'latest' e as demais como 'history'
|
|
$task->statusAmbit = $task->departure_date === $group->first()->departure_date ? 'latest' : 'history';
|
|
return $task;
|
|
});
|
|
})
|
|
->flatten(1); // Remove o agrupamento aninhado para que todos estejam em uma única coleção
|
|
|
|
|
|
// 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();
|
|
|
|
// Cria uma estrutura padrão para tarefas não concluídas
|
|
$receiveAllTasksHistiory->push((object) [
|
|
'elemental_tasks_id' => $taskId,
|
|
'control_equipment_workstation_id' => 'N/A',
|
|
// 'cardType' => 'blue',
|
|
'cardTypeStyle' => 'gray',
|
|
'formatted_answers' => [],
|
|
'entry_date' => 'N/A',
|
|
'runtime' => 'N/A',
|
|
'statusAmbit' => 'incomplete', // Novo status para tarefas incompletas
|
|
'typeStatusHistory' => 'N/A',
|
|
'elementalTask' => (object) [
|
|
'elemental_tasks_code' => $elementalTask ? $elementalTask->elemental_tasks_code : null,
|
|
'elemental_tasks_description' => $elementalTask ? $elementalTask->elemental_tasks_description : null
|
|
]
|
|
]);
|
|
}
|
|
|
|
$dataControlEquipment = ['typePageForViewElementalTasks' => 'historic'];
|
|
|
|
|
|
|
|
return view('projectsClients.showAmbitDetailProjectHistory', compact('receiveComments', 'equipmentStatus', 'detailsProject', 'receiveAmbit', 'receiveAllTasksHistiory', 'detalsEquipment', 'detailsEquipmentWorkProject', 'dataControlEquipment'));
|
|
|
|
}
|
|
|
|
// 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;
|
|
}
|
|
|
|
// Cria um sistema de 1 a 3 , onde 1 e apenas 'ler', 2 apenas editar e 3 as 2 opcoes
|
|
$portfolioOnlyreadOrEditToo = 3;
|
|
//filteredTasks', 'OrdemTasks', 'DetailsTasks' campos vazios para ISV.
|
|
return view('projectsClients.articulated_2_ShowEquipment', compact('detailsProject', 'dataEquipment', 'filteredTasks', 'OrdemTasks', 'DetailsTasks', 'specificAttributesArray', 'receiveEquipmentWorkHistorys', 'portfolioOnlyreadOrEditToo'));
|
|
}
|
|
|
|
//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;
|
|
}
|
|
|
|
// Cria um sistema de 1 a 3 , onde 1 e apenas 'ler', 2 apenas editar e 3 as 2 opcoes
|
|
$portfolioOnlyreadOrEditToo = 3;
|
|
|
|
return view('projectsClients.testRoute', compact('dataEquipment', 'receiveAlldetailsEquipmentWorkHistory', 'specificAttributesArray', 'portfolioOnlyreadOrEditToo'));
|
|
|
|
}
|
|
|
|
|
|
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');
|
|
}
|
|
|
|
}
|