1754 lines
82 KiB
PHP
Executable File
1754 lines
82 KiB
PHP
Executable File
<?php
|
|
|
|
namespace App\Http\Controllers;
|
|
|
|
use App\Models\EquipmentWorkHistory;
|
|
use Illuminate\Http\Request;
|
|
use Illuminate\Support\Facades\DB;
|
|
use PhpOffice\PhpSpreadsheet\IOFactory;
|
|
|
|
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
|
|
use Symfony\Component\HttpFoundation\StreamedResponse;
|
|
|
|
|
|
use App\Models\User;
|
|
use App\Models\CompanyProject;
|
|
use App\Models\Unit;
|
|
use App\Models\EquipmentType;
|
|
use App\Models\Equipment;
|
|
use App\Models\Plant;
|
|
use App\Models\SpecificAttributesEquipmentType;
|
|
use App\Models\GeneralAttributesEquipment;
|
|
use App\Models\PendingEquipment;
|
|
use App\Models\AmbitsEquipment;
|
|
use App\Models\EquipmentAssociationAmbit;
|
|
use App\Models\ConstructionWorkstation;
|
|
use App\Models\ElementalTasks;
|
|
use App\Models\OrderEquipmentTasks;
|
|
use App\Models\FurtherTasks;
|
|
use App\Models\WorkstationsAssociationTasks;
|
|
use App\Models\TasksAssociationAmbits;
|
|
use App\Models\QrcodesAssociatedEquipment;
|
|
|
|
use LengthException;
|
|
|
|
// use DataTables;
|
|
|
|
|
|
class CreateProjectController extends Controller
|
|
{
|
|
public function changeStateProject($projectId)
|
|
{
|
|
$detailsPrpject = CompanyProject::where('company_projects_id', $projectId)->first();
|
|
$detailsPrpject->order_project = 3;
|
|
$detailsPrpject->save();
|
|
|
|
// Redireciona para a rota 'home' após alterar o estado para Execussao
|
|
return redirect()->route('home');
|
|
}
|
|
|
|
public function deleteProject($projectId)
|
|
{
|
|
|
|
// Encontra o projeto pelo ID
|
|
$deleteProject = CompanyProject::where('company_projects_id', $projectId)->first();
|
|
|
|
if ($deleteProject) {
|
|
// Busca todas as ConstructionWorkstation associadas ao projeto
|
|
$workstations = ConstructionWorkstation::where('company_projects_id', $projectId)->get();
|
|
|
|
foreach ($workstations as $workstation) {
|
|
// Para cada workstation, busca usuários com o mesmo nome
|
|
$user = User::where('user_name', $workstation->name_workstations)->first();
|
|
|
|
if ($user) {
|
|
$user->delete();
|
|
}
|
|
}
|
|
|
|
// Deleta o projeto após processar as workstations
|
|
$deleteProject->delete();
|
|
|
|
// Redireciona para a rota 'home' após a deleção
|
|
return redirect()->route('home');
|
|
}
|
|
|
|
}
|
|
|
|
public function changeAmbitEquipment(Request $request)
|
|
{
|
|
|
|
$receiveAmbitEquipmentId = $request->receveAmbit;
|
|
$equipmentId = $request->equipmentID;
|
|
|
|
$receiveEquipment = Equipment::where('equipment_id', $equipmentId)->first();
|
|
|
|
$receiveEquipmentWorkHistorys = EquipmentWorkHistory::where('equipment_id', $receiveEquipment->equipment_id)
|
|
->where('company_projects_id', $receiveEquipment->company_projects_id)
|
|
->first();
|
|
|
|
$receiveDataEquipmentAssociationAmbit = EquipmentAssociationAmbit::where('equipmentWorkHistorys_id', $receiveEquipmentWorkHistorys->equipmentWorkHistorys_id)->first();
|
|
|
|
if ($receiveDataEquipmentAssociationAmbit->ambits_id == $receiveAmbitEquipmentId) {
|
|
return back()->with('danger', 'Âmbito selecionado é igual ao anterior!');
|
|
} else {
|
|
// Deleta as tarefas associadas ao equipamento no âmbito atual
|
|
OrderEquipmentTasks::where('equipmentWorkHistorys_id', $receiveEquipmentWorkHistorys->equipmentWorkHistorys_id)->delete();
|
|
|
|
// Atualiza o âmbito do equipamento
|
|
$receiveDataEquipmentAssociationAmbit->ambits_id = $receiveAmbitEquipmentId;
|
|
$receiveDataEquipmentAssociationAmbit->save();
|
|
|
|
// Insere as novas tarefas para o novo âmbito
|
|
$TasksAssociationAmbits = TasksAssociationAmbits::where('ambits_equipment_id', $receiveAmbitEquipmentId)->get();
|
|
$execution_order = 1;
|
|
foreach ($TasksAssociationAmbits as $TasksAssociationAmbit) {
|
|
$JoinsEquipmentsWithTasks = new OrderEquipmentTasks;
|
|
$JoinsEquipmentsWithTasks->equipmentWorkHistorys_id = $receiveEquipmentWorkHistorys->equipmentWorkHistorys_id;
|
|
$JoinsEquipmentsWithTasks->execution_order = $execution_order++;
|
|
$JoinsEquipmentsWithTasks->elemental_tasks_id = $TasksAssociationAmbit->elemental_tasks_id;
|
|
$JoinsEquipmentsWithTasks->further_tasks_id = null;
|
|
$JoinsEquipmentsWithTasks->inspection = 2; // ou outro valor conforme necessário
|
|
$JoinsEquipmentsWithTasks->save();
|
|
}
|
|
|
|
return back()->with('success', 'Equipamento: ' . $receiveEquipment->equipment_id . ' trocado de âmbito com sucesso!');
|
|
}
|
|
|
|
}
|
|
|
|
public function deleteEquipmentInProject(Request $request)
|
|
{
|
|
$receiveEquipment = Equipment::where('equipment_id', $request->equipmentId)->first();
|
|
$receiveStatus = $request->deleteEquipmentProject;
|
|
|
|
//Independente do tipo de select ele vai deletar o equipamento do Historico
|
|
EquipmentWorkHistory::where('equipment_id', $receiveEquipment->equipment_id)
|
|
->where('company_projects_id', $receiveEquipment->company_projects_id)
|
|
->delete();
|
|
|
|
// Deleta o equipamento por completo e retorna
|
|
if ($receiveStatus == 'complete') {
|
|
$receiveEquipment->delete();
|
|
|
|
return redirect()->back()
|
|
->with('success', 'Equipamento: ' . $receiveEquipment->equipment_id . ' excluído com sucesso!');
|
|
} else {
|
|
// Deleta apaga a associacao do equipamento a Obra
|
|
$receiveEquipment->company_projects_id = null;
|
|
$receiveEquipment->save();
|
|
|
|
return redirect()->back()
|
|
->with('success', 'Equipamento: ' . $receiveEquipment->equipment_id . ' retirado da obra com sucesso!');
|
|
}
|
|
}
|
|
|
|
|
|
|
|
public function deletePendingEquipments(Request $request)
|
|
{
|
|
$pendingEquipmentIds = $request->input('pendingEquipmentIds', []);
|
|
|
|
// Verifica se o array não está vazio
|
|
if (!empty($pendingEquipmentIds)) {
|
|
// Deleta todos os registros de PendingEquipment que correspondam aos IDs
|
|
PendingEquipment::whereIn('pending_equipment_id', $pendingEquipmentIds)->delete();
|
|
}
|
|
|
|
return redirect()->back()
|
|
->with('success', 'Todos os equipamentos pendentes apagados com sucesso!');
|
|
}
|
|
|
|
|
|
public function receiveUnits($numberProject)
|
|
{
|
|
$PlantData = CompanyProject::where('company_projects_id', $numberProject)->first();
|
|
|
|
if (!$PlantData) {
|
|
return response()->json([]);
|
|
}
|
|
|
|
$receiveUnits = Unit::where('plant_id', $PlantData->plant_id)->get();
|
|
|
|
// Formatar a resposta para o formato esperado pelo JavaScript
|
|
$formattedUnits = $receiveUnits->map(function ($unit) {
|
|
return [
|
|
'id' => $unit->receiveUnits, // Ajuste para o nome da sua coluna correta
|
|
'name' => $unit->unit_name // Ajuste para o nome da sua coluna correta
|
|
];
|
|
});
|
|
|
|
return response()->json($formattedUnits);
|
|
}
|
|
|
|
|
|
public function deleteFurtherTasks(Request $request)
|
|
{
|
|
$receiveDataEquipment = Equipment::where('equipment_id', $request->equipmentID)->first();
|
|
// Buscar os registros que correspondem ao equipmentID e que têm further_tasks_id nos selectedTasks
|
|
$tasksToDelete = OrderEquipmentTasks::where('equipment_id', $request->equipmentID)
|
|
->whereIn('further_tasks_id', $request->selectedTasks)
|
|
->get();
|
|
|
|
// Excluir esses registros
|
|
foreach ($tasksToDelete as $task) {
|
|
$task->delete();
|
|
}
|
|
|
|
// Se o treatmentFurtherTask for "DeleteFurtherTask", exclua os registros da tabela principal FurtherTasks
|
|
if ($request->treatmentFurtherTask == "DeleteFurtherTask") {
|
|
FurtherTasks::whereIn('further_tasks_id', $request->selectedTasks)->delete();
|
|
}
|
|
|
|
// Reordenar os registros restantes
|
|
$remainingTasks = OrderEquipmentTasks::where('equipment_id', $request->equipmentID)
|
|
->orderBy('execution_order', 'asc')
|
|
->get();
|
|
|
|
$executionOrder = 1;
|
|
foreach ($remainingTasks as $task) {
|
|
$task->execution_order = $executionOrder;
|
|
$task->save();
|
|
$executionOrder++;
|
|
}
|
|
return redirect()->back()->with('success', 'Ordem de execução do equipamento: ' . $receiveDataEquipment->equipment_tag . ' Atulizada!');
|
|
}
|
|
|
|
public function addFurtherTasks(Request $request)
|
|
{
|
|
// Recebe e organiza os dados do equipameto recebido : ($request->equipmentID) e organiza em asc de acordo com a Ordem de execução
|
|
// $equipmentId = $request->equipmentID;
|
|
// $tasksToReorder = OrderEquipmentTasks::where('equipment_id', $equipmentId)
|
|
// ->orderBy('execution_order', 'asc')
|
|
// ->get();
|
|
|
|
$receiveDataEquipment = Equipment::where('equipment_id', $request->equipmentID)->first();
|
|
|
|
$receiveEquipmentWorkHistory = EquipmentWorkHistory::where('equipment_id', $request->equipmentID)
|
|
->where('company_projects_id', $receiveDataEquipment->company_projects_id)
|
|
->first();
|
|
|
|
|
|
// *Para Criar uma nova Tarefa complementar deve ser a soma dos dados das 2 tabelas para dar o numero da proxima tarefa e assim o numero da TC
|
|
// Obtenha a contagem de registros nas tabelas ElementalTasks e FurtherTasks
|
|
$elementalTasksCount = ElementalTasks::count();
|
|
$furtherTasksCount = FurtherTasks::count();
|
|
|
|
// Calcule o valor de further_tasks_id
|
|
$newFurtherTaskId = $elementalTasksCount + $furtherTasksCount + 1;
|
|
|
|
// Calcule o valor de further_tasks_name
|
|
$newFurtherTaskName = 'TC' . ($furtherTasksCount + 1);
|
|
|
|
|
|
|
|
$insertPosition = $request->ArrayListElementsTasks + 1;
|
|
|
|
// Incrementar a execution_order das tarefas após a posição de inserção
|
|
// foreach ($tasksToReorder as $task) {
|
|
// if ($task->execution_order >= $insertPosition) {
|
|
// $task->execution_order += 1;
|
|
// $task->save();
|
|
// }
|
|
// }
|
|
|
|
// Agora, insira a nova tarefa na posição desejada
|
|
$newOrderEquipmentTask = new OrderEquipmentTasks;
|
|
$newOrderEquipmentTask->equipmentWorkHistorys_id = $receiveEquipmentWorkHistory->equipmentWorkHistorys_id;
|
|
$newOrderEquipmentTask->execution_order = null;
|
|
$newOrderEquipmentTask->elemental_tasks_id = null;
|
|
|
|
// Se o selectedFurtherTaskExisting for null quer dizer que e uma TC complementar criada e nova se nao for null quer dizer que vamos criar uma TC existente.
|
|
if ($request->selectedFurtherTaskExisting == 'null') {
|
|
|
|
// Cria uma nova tarefa Complementar
|
|
$newFurtherTask = new FurtherTasks;
|
|
$newFurtherTask->further_tasks_id = $newFurtherTaskId;
|
|
$newFurtherTask->further_tasks_name = $newFurtherTaskName;
|
|
$newFurtherTask->further_tasks_description = $request->furtherTask;
|
|
$newFurtherTask->company_projects_id = $receiveDataEquipment->company_projects_id;
|
|
$newFurtherTask->save();
|
|
|
|
$newOrderEquipmentTask->further_tasks_id = $newFurtherTask->further_tasks_id;
|
|
} else {
|
|
$newOrderEquipmentTask->further_tasks_id = $request->selectedFurtherTaskExisting;
|
|
}
|
|
|
|
$newOrderEquipmentTask->inspection = 2;
|
|
$newOrderEquipmentTask->save();
|
|
|
|
return redirect()->back()->with('success', 'Ordem de execução do equipamento: ' . $receiveDataEquipment->equipment_tag . ' Atulizada!');
|
|
}
|
|
|
|
|
|
public function receiveEquipmentToAssociateTasks(Request $request)
|
|
{
|
|
$receiveIsptNumber = 0;
|
|
|
|
// Obter o maior ispt_number da tabela EquipmentWorkHistory que corresponde aos valores em Equipment
|
|
$highestIsptNumber = EquipmentWorkHistory::select('equipment_work_historys.ispt_number')
|
|
->join('equipments', function ($join) {
|
|
$join->on('equipments.equipment_id', '=', 'equipment_work_historys.equipment_id')
|
|
->on('equipments.company_projects_id', '=', 'equipment_work_historys.company_projects_id');
|
|
})
|
|
->orderBy('equipment_work_historys.ispt_number', 'desc')
|
|
->first();
|
|
|
|
// Se existir, ele busca o maior número e acrescenta mais um para adicionar um novo equipamento.
|
|
if ($highestIsptNumber) {
|
|
|
|
$receiveIsptNumber = $highestIsptNumber->ispt_number + 1;
|
|
} else {
|
|
// Se não houver registros, comece com 1
|
|
$receiveIsptNumber = 1;
|
|
}
|
|
|
|
$execution_order = 1;
|
|
|
|
foreach ($request->equipment as $equipment) {
|
|
$equipmentModel = Equipment::where('equipment_id', $equipment['equipment_id'])->first();
|
|
|
|
//Atualiza a tabela equipment para associar o equipamento a uma Obra.
|
|
if ($equipmentModel) {
|
|
$equipmentModel->company_projects_id = $request->receiveNumberProject;
|
|
$equipmentModel->save();
|
|
|
|
// Ja associado, criar dados nos Historico para depois ser possivel de acessar.
|
|
$createEquipmentWorkHistory = new EquipmentWorkHistory;
|
|
$createEquipmentWorkHistory->equipment_id = $equipment['equipment_id'];
|
|
$createEquipmentWorkHistory->ispt_number = $receiveIsptNumber++;
|
|
$createEquipmentWorkHistory->company_projects_id = $request->receiveNumberProject;
|
|
$createEquipmentWorkHistory->save();
|
|
|
|
//Criar associacao do equipamento ao Âmbito
|
|
$AssociationEquipmentAmbit = new EquipmentAssociationAmbit;
|
|
$AssociationEquipmentAmbit->equipment_type_id = $equipment['equipment_type_id'];
|
|
$AssociationEquipmentAmbit->ambits_id = $equipment['ambit_id'];
|
|
$AssociationEquipmentAmbit->equipmentWorkHistorys_id = $createEquipmentWorkHistory->equipmentWorkHistorys_id;
|
|
$AssociationEquipmentAmbit->save();
|
|
|
|
//Recebe a tabela com as associoacoes entre Âmbitos e tarefas Elementares
|
|
$TasksAssociationAmbits = TasksAssociationAmbits::all()->where('ambits_equipment_id', $AssociationEquipmentAmbit->ambits_id);
|
|
|
|
foreach ($TasksAssociationAmbits as $TasksAssociationAmbit) {
|
|
$JoinsEquipmentsWithTasks = new OrderEquipmentTasks;
|
|
$JoinsEquipmentsWithTasks->equipmentWorkHistorys_id = $createEquipmentWorkHistory->equipmentWorkHistorys_id;
|
|
$JoinsEquipmentsWithTasks->execution_order = $execution_order++;
|
|
$JoinsEquipmentsWithTasks->elemental_tasks_id = $TasksAssociationAmbit->elemental_tasks_id;
|
|
$JoinsEquipmentsWithTasks->further_tasks_id = null;
|
|
$JoinsEquipmentsWithTasks->inspection = 2;
|
|
$JoinsEquipmentsWithTasks->save();
|
|
}
|
|
}
|
|
}
|
|
|
|
return redirect()->back()->with('success', 'Equipametos associados a Obra com Sucesso !');
|
|
}
|
|
|
|
public function receiveUnitsForExcelTemplate($numberProject)
|
|
{
|
|
// Dados do Projecto
|
|
$receveCompanyProject = CompanyProject::where('company_projects_id', $numberProject)->first();
|
|
// Dados da Instalação
|
|
$recevePlant = Plant::where('plant_id', $receveCompanyProject->plant_id)->first();
|
|
// Dados das Fabricas
|
|
$receveUnits = Unit::where('plant_id', $recevePlant->plant_id)->get();
|
|
|
|
// dd($receveUnits);
|
|
$filePath = public_path('templateExcel/Valves_Template.xlsx');
|
|
// Load the spreadsheet
|
|
$spreadsheet = IOFactory::load($filePath);
|
|
// Get the second sheet
|
|
$sheet = $spreadsheet->getSheet(1); // Sheet index starts from 0
|
|
$row = 2; // Row number where you want to start inserting data
|
|
foreach ($receveUnits as $unit) {
|
|
// Set value for column D
|
|
$sheet->setCellValue('A' . $row, $unit->unit_name);
|
|
$row++;
|
|
}
|
|
|
|
$formattedDateTime = date('Y-m-d_H-i'); // Formato: Ano-Mês-Dia_Hora-Minuto
|
|
$fileName = "Valves_Template_{$numberProject}_{$formattedDateTime}.xlsx";
|
|
|
|
// Generate and return the download response
|
|
// return $this->createDownloadResponse($spreadsheet, 'Valves_Template.xlsx');
|
|
return $this->createDownloadResponse($spreadsheet, $fileName);
|
|
}
|
|
|
|
protected function createDownloadResponse($spreadsheet, $filename)
|
|
{
|
|
// Create a writer object
|
|
$writer = new Xlsx($spreadsheet);
|
|
// Create a StreamedResponse with a callback
|
|
$response = new StreamedResponse(
|
|
function () use ($writer) {
|
|
$writer->save('php://output');
|
|
}
|
|
);
|
|
// Set headers to indicate we're sending an Excel file
|
|
$response->headers->set('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
|
|
$response->headers->set('Content-Disposition', 'attachment;filename="' . $filename . '"');
|
|
$response->headers->set('Cache-Control', 'max-age=0');
|
|
|
|
return $response;
|
|
}
|
|
|
|
public function finishCreatingProject($numberProject)
|
|
{
|
|
// recebe atraves de sessao toda a vez quem entra no componente 'SelectElementalTasksInWonkstation' para selecionar as tarefas de cada Workstation
|
|
$receiveAllFurtherTasks = session('receiveAllFurtherTasks');
|
|
$receiveElementalTasks = session('receiveElementalTasks');
|
|
|
|
// Inicializar a matriz de IDs faltantes
|
|
$missingElementalTasks = [];
|
|
$missingFurtherTasksDetails = [];
|
|
$missingWorkstations = [];
|
|
|
|
// Recebe todos os dados dos postos de Trabalho
|
|
$receiveWorkstaions = ConstructionWorkstation::where('company_projects_id', $numberProject)->get();
|
|
|
|
foreach ($receiveWorkstaions as $workstation) {
|
|
// Verifica se o ID da workstation está presente na tabela WorkstationsAssociationTasks
|
|
$exists = WorkstationsAssociationTasks::where('id_workstations', $workstation->id_workstations)->exists();
|
|
|
|
// Se não existe na tabela, adiciona à lista das workstations onde nao tem tarefas atribuidas ainda.
|
|
if (!$exists) {
|
|
$missingWorkstations[$workstation->id_workstations] = [
|
|
'name_workstations' => $workstation->name_workstations,
|
|
'nomenclature_workstation' => $workstation->nomenclature_workstation
|
|
];
|
|
}
|
|
}
|
|
|
|
// Extrai apena o id_workstations de cada um
|
|
$workstationIds = $receiveWorkstaions->pluck('id_workstations')->toArray();
|
|
|
|
// Iterar sobre cada tarefa em $receiveElementalTasks
|
|
foreach ($receiveElementalTasks as $taskGroup) {
|
|
foreach ($taskGroup as $taskId => $taskDetails) {
|
|
// Verificar se a tarefa está associada a algum id_workstations
|
|
$exists = WorkstationsAssociationTasks::whereIn('id_workstations', $workstationIds)
|
|
->where('elemental_tasks_id', $taskId)
|
|
->exists();
|
|
|
|
// Se não existe, adicionar à lista de tarefas faltantes
|
|
if (!$exists) {
|
|
$missingElementalTasks[$taskId] = $taskDetails;
|
|
}
|
|
}
|
|
}
|
|
|
|
// Iterar sobre cada tarefa em $receiveAllFurtherTasks
|
|
foreach ($receiveAllFurtherTasks as $furtherTask) {
|
|
// Obter o ID da tarefa
|
|
$taskId = $furtherTask->further_tasks_id;
|
|
|
|
// Verificar se a tarefa está associada a algum id_workstations
|
|
$exists = WorkstationsAssociationTasks::whereIn('id_workstations', $workstationIds)
|
|
->where('further_tasks_id', $taskId)
|
|
->exists();
|
|
|
|
// Se não existe, adicionar à lista de tarefas faltantes
|
|
if (!$exists) {
|
|
$missingFurtherTasksDetails[$taskId] = [
|
|
'name' => $furtherTask->further_tasks_name,
|
|
'description' => $furtherTask->further_tasks_description
|
|
];
|
|
}
|
|
}
|
|
|
|
// A Partir daqui ja temos as 2 variaveis a receberem array com as tarefas que faltam ser associadas.
|
|
$allMissingTasks = [
|
|
'elemental' => $missingElementalTasks,
|
|
'further' => $missingFurtherTasksDetails,
|
|
'workstation' => $missingWorkstations
|
|
];
|
|
// Verificar se todos os arrays internos estão vazios
|
|
$isEmpty = empty($allMissingTasks['elemental']) && empty($allMissingTasks['further']) && empty($allMissingTasks['workstation']);
|
|
|
|
if (!$isEmpty) {
|
|
return redirect()->back()->with('errors', $allMissingTasks);
|
|
} else {
|
|
$project = CompanyProject::find($numberProject);
|
|
$project->order_project = 2;
|
|
$project->save();
|
|
|
|
return redirect()->route('home');
|
|
}
|
|
}
|
|
|
|
public function deleteWorkstation($name)
|
|
{
|
|
$workstation = ConstructionWorkstation::where('name_workstations', $name)->first();
|
|
$removeAcountUserWorkstation = User::where('user_name', $workstation->name_workstations)->first();
|
|
|
|
if ($workstation && $removeAcountUserWorkstation) {
|
|
$workstation->delete();
|
|
$removeAcountUserWorkstation->delete();
|
|
|
|
// pegar o número da estação de trabalho que está sendo deletada
|
|
preg_match('/workstation(\d+)-/', $workstation->name_workstations, $matches);
|
|
$deletedWorkstationNumber = $matches[1];
|
|
|
|
// pega o número do projeto da estação de trabalho que está sendo deletada
|
|
$projectNumber = explode('-', $workstation->name_workstations)[1];
|
|
|
|
// pegar todas as estações de trabalho e Utilizadors com números maiores que o deletado e renumerá-los
|
|
$workstationsToUpdate = ConstructionWorkstation::where('company_projects_id', $projectNumber)
|
|
->whereRaw("SUBSTRING_INDEX(name_workstations, '-', 1) REGEXP '^workstation[0-9]+$'")
|
|
->whereRaw("CAST(SUBSTRING(SUBSTRING_INDEX(name_workstations, '-', 1), 12) AS UNSIGNED) >= ?", [$deletedWorkstationNumber])
|
|
->orderByRaw("CAST(SUBSTRING(SUBSTRING_INDEX(name_workstations, '-', 1), 12) AS UNSIGNED) DESC")
|
|
->get();
|
|
|
|
foreach ($workstationsToUpdate as $workstationToUpdate) {
|
|
// pegar o número da estação de trabalho atual
|
|
preg_match('/workstation(\d+)-/', $workstationToUpdate->name_workstations, $matches);
|
|
$currentWorkstationNumber = $matches[1];
|
|
|
|
// atualizar nome da estação de trabalho
|
|
$workstationToUpdate->name_workstations = 'workstation' . ($currentWorkstationNumber - 1) . '-' . $projectNumber;
|
|
$workstationToUpdate->save();
|
|
|
|
// atualizar Utilizador associado
|
|
$userToUpdate = User::where('user_name', 'workstation' . $currentWorkstationNumber . '-' . $projectNumber)->first();
|
|
if ($userToUpdate) {
|
|
$userToUpdate->user_name = 'workstation' . ($currentWorkstationNumber - 1) . '-' . $projectNumber;
|
|
$userToUpdate->save();
|
|
}
|
|
}
|
|
|
|
return back()->with('success', 'Posto de Trabalho removido com sucesso!');
|
|
}
|
|
return back()->with('danger', 'Posto de Trabalho não encontrado!');
|
|
}
|
|
|
|
public function removeProjectEquipment(Request $request)
|
|
{
|
|
|
|
$equipment = Equipment::find($request->EquipmentID);
|
|
|
|
if ($request->removalType == 'total') {
|
|
$equipment->delete();
|
|
|
|
return back()->with('success', 'Equipamento Excluido com sucesso!');
|
|
} else
|
|
$equipment->company_projects_id = null;
|
|
$equipment->save();
|
|
|
|
return back()->with('success', 'Equipamento retirado da obra !');
|
|
}
|
|
public function EditEquipment(Request $request)
|
|
{
|
|
|
|
// Localiza o equipment pelo numberProject
|
|
$dataEquipment = Equipment::where('equipment_tag', $request->tag)->first();
|
|
|
|
$receiveEquipmentWorkHistori = EquipmentWorkHistory::where('equipment_id', $dataEquipment->equipment_id)
|
|
->where('company_projects_id', $dataEquipment->company_projects_id)
|
|
->first();
|
|
|
|
// Atualiza os campos
|
|
$dataEquipment->equipment_tag = $request->tag;
|
|
$dataEquipment->equipment_description = $request->equipmentDescription;
|
|
$dataEquipment->equipment_serial_number = $request->serialNumberEquipment;
|
|
$dataEquipment->equipment_brand = $request->equipmentBrand;
|
|
$dataEquipment->equipment_model = $request->equipmentModel;
|
|
|
|
$dataEquipment->save();
|
|
|
|
if ($request->input('attributes')) {
|
|
foreach ($request->input('attributes') as $key => $value) {
|
|
// Verifica se o valor é null e a chave é um número (correspondendo aos general_attributes_equipment_id)
|
|
if ($value == null && is_numeric($key)) {
|
|
// Procura o registro relevante em SpecificAttributesEquipmentType
|
|
$specificAttributes = SpecificAttributesEquipmentType::where('equipment_id', $dataEquipment->equipment_id)
|
|
->where('general_attributes_equipment_id', $key)
|
|
->first();
|
|
|
|
// Se o registro existir, o deleta
|
|
if ($specificAttributes) {
|
|
$specificAttributes->delete();
|
|
}
|
|
}
|
|
// Se o valor não for null, atualiza ou cria um novo registro
|
|
elseif ($value !== null && is_numeric($key)) {
|
|
|
|
// Procura o registro relevante em SpecificAttributesEquipmentType
|
|
$specificAttributes = SpecificAttributesEquipmentType::where('equipment_id', $dataEquipment->equipment_id)
|
|
->where('general_attributes_equipment_id', $key)
|
|
->first();
|
|
|
|
// Se o registro existir, atualiza o valor
|
|
if ($specificAttributes) {
|
|
$specificAttributes->specific_attributes_value = $value;
|
|
$specificAttributes->save();
|
|
}
|
|
// Se não existir, cria um novo
|
|
else {
|
|
// Cria um novo registro em SpecificAttributesEquipmentType
|
|
$specificAttributes = new SpecificAttributesEquipmentType();
|
|
$specificAttributes->equipment_id = $dataEquipment->equipment_id;
|
|
$specificAttributes->equipment_type_id = $dataEquipment->equipment_type_id;
|
|
$specificAttributes->general_attributes_equipment_id = $key;
|
|
$specificAttributes->specific_attributes_value = $value;
|
|
$specificAttributes->save();
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
|
|
// dd($request);
|
|
// 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 : ' . $equipment->equipment_tag);
|
|
// }
|
|
// $executionOrder = 1;
|
|
|
|
|
|
// foreach ($request->input('ordemTasks') as $key => $value) {
|
|
// $orderEquipmentTask = OrderEquipmentTasks::where('equipment_id', $request->equipmentId)
|
|
// ->where('elemental_tasks_id', $key)
|
|
// ->first();
|
|
|
|
// if ($value == "on") {
|
|
// if (!$orderEquipmentTask) {
|
|
// if ($receiveEquipmentWorkHistori && $receiveEquipmentWorkHistori <> null) {
|
|
// $orderEquipmentTask = new OrderEquipmentTasks();
|
|
// $orderEquipmentTask->equipment_id = $request->equipmentId;
|
|
// $orderEquipmentTask->elemental_tasks_id = $key;
|
|
// }
|
|
|
|
// }
|
|
// //Nal precisa mais indicar a ordem das tarefas pois ela agora nao vao ser feitas por ordem necessariamente
|
|
// $orderEquipmentTask->execution_order = null;
|
|
// $orderEquipmentTask->save();
|
|
|
|
// $executionOrder++;
|
|
// } elseif ($value == "off" && $orderEquipmentTask) {
|
|
// $orderEquipmentTask->delete();
|
|
// }
|
|
// }
|
|
|
|
|
|
// // $executionOrder = 1; // Reinicia a contagem de ordem de execução
|
|
// $remainingOrderEquipmentTasks = OrderEquipmentTasks::where('equipment_id', $request->equipmentId)
|
|
// ->orderBy('execution_order', 'asc')
|
|
// ->get();
|
|
|
|
// foreach ($remainingOrderEquipmentTasks as $orderEquipmentTask) {
|
|
// $orderEquipmentTask->execution_order = null;
|
|
// $orderEquipmentTask->save();
|
|
// $executionOrder++;
|
|
// }
|
|
|
|
// $orderTasks = OrderEquipmentTasks::where('equipment_id', $request->equipmentId)
|
|
// ->orderBy('execution_order', 'asc')
|
|
// ->get();
|
|
|
|
// $taskExecutionOrders = [];
|
|
// foreach ($orderTasks as $task) {
|
|
// $taskExecutionOrders[$task->elemental_tasks_id] = $task->execution_order;
|
|
// }
|
|
|
|
// Retorna uma resposta
|
|
// return redirect()->route('articulated_2', ['id' => $request->numberProject])
|
|
// ->with('success', 'Equipamento ' . $dataEquipment->equipment_tag . ' Editado com Sucesso!!!');
|
|
// ->with('taskExecutionOrders', $taskExecutionOrders);
|
|
|
|
// return back()->with('success', 'Ação concluída com sucesso!')
|
|
return back();
|
|
|
|
}
|
|
|
|
public function showJson($id)
|
|
{
|
|
$attributes = SpecificAttributesEquipmentType::where('equipment_id', $id)->get();
|
|
$OrdemTasks = OrderEquipmentTasks::where('equipment_id', $id)->get();
|
|
$allElementalTasks = ElementalTasks::all();
|
|
|
|
return response()->json([
|
|
'attributes' => $attributes,
|
|
'OrdemTasks' => $OrdemTasks,
|
|
'allElementalTasks' => $allElementalTasks
|
|
]);
|
|
}
|
|
|
|
public function receveTasksWorkstationPlanning($WorkstationId)
|
|
{
|
|
$workstationsAssociationTasks = WorkstationsAssociationTasks::where('id_workstations', $WorkstationId)->get();
|
|
|
|
return response()->json([
|
|
'workstationsAssociationTasks' => $workstationsAssociationTasks
|
|
]);
|
|
}
|
|
|
|
|
|
public function createWorkStations(Request $request)
|
|
{
|
|
// Pega o número de estações de trabalho do request
|
|
$numberWorkstations = $request->numberWorkstations;
|
|
|
|
// Pega o número do projeto do request
|
|
$numberProject = $request->numberProject;
|
|
|
|
$listWorkstations = ConstructionWorkstation::where('company_projects_id', $numberProject)->get();
|
|
$receveProjectCompanyNumber = CompanyProject::where('company_projects_id', $numberProject)->first();
|
|
|
|
// Pega o último elemento da lista
|
|
$lastWorkstation = $listWorkstations->last();
|
|
|
|
|
|
// Se houver uma estação de trabalho anterior, extrai o número dela
|
|
$startNumber = 1;
|
|
if ($lastWorkstation) {
|
|
$parts = explode('-', $lastWorkstation->name_workstations);
|
|
$startNumber = intval(str_replace('workstation', '', $parts[0])) + 1;
|
|
}
|
|
|
|
// Loop para criar as estações de trabalho e seus logins
|
|
for ($i = $startNumber; $i < $startNumber + $numberWorkstations; $i++) {
|
|
$workstation = new ConstructionWorkstation();
|
|
$workstation->name_workstations = 'workstation' . $i . '-' . $numberProject;
|
|
$workstation->company_projects_id = $numberProject;
|
|
$workstation->save();
|
|
|
|
preg_match('/workstation(\d+)-/', $workstation->name_workstations, $matches);
|
|
$receiveNumberWorkstation = $matches[1];
|
|
|
|
//Apos criar a Workstation vamos criar um login para pode aceder os postos de trabalho na obra
|
|
$loginWorkStation = new User;
|
|
$loginWorkStation->user_name = $workstation->name_workstations;
|
|
$loginWorkStation->email = $receveProjectCompanyNumber->project_company_number . '-' . $receiveNumberWorkstation . '@isptgroup.com';
|
|
$loginWorkStation->password = bcrypt($receveProjectCompanyNumber->project_company_number . '-' . $receiveNumberWorkstation);
|
|
$loginWorkStation->type_users = 5;
|
|
$loginWorkStation->user_nif = $receveProjectCompanyNumber->project_company_number . '-' . $receiveNumberWorkstation;
|
|
$loginWorkStation->save();
|
|
}
|
|
|
|
// Redireciona para onde você quiser após a criação das workstations
|
|
return redirect()->route('workStation_3', ['id' => $request->numberProject])
|
|
->with('success', $numberWorkstations . ' Postos de Trabalho criados !!!')
|
|
->with('listWorkstations', $listWorkstations);
|
|
}
|
|
|
|
|
|
// Funcao apenas para retornar os dados necessarios para a view criar uma Obra.
|
|
public function createProjectForStep1()
|
|
{
|
|
$companies = User::where('type_users', 3)->get();
|
|
// Apos terminar não vai ficar step 1
|
|
return view('projectsClients/createProject', ['step' => 1], ['companies' => $companies]);
|
|
}
|
|
|
|
// Progress Bar
|
|
//Devolve para a primeira para na Descrição do projecto apenas user com ID 3, quer dizer que apenas as "empresas"
|
|
public function showStep1($company_projects_id)
|
|
{
|
|
// $projects = CompanyProject::find($company_projects_id);
|
|
|
|
$projects = CompanyProject::with('user')->find($company_projects_id);
|
|
// dd($projects->user);
|
|
|
|
$companies = User::where('type_users', 3)->get();
|
|
|
|
$receiveDetailsPlant = Plant::where('plant_id', $projects->plant_id)->first();
|
|
|
|
$receiveDetailsUser = User::where('user_id', $receiveDetailsPlant->user_id)->first();
|
|
// $receiveDetailsUser->plantName = $receiveDetailsPlant->plant_name;
|
|
|
|
$projects->plantName = $receiveDetailsPlant->plant_name;
|
|
$projects->userName = $receiveDetailsUser->user_name;
|
|
|
|
return view('projectsClients/projectDetails_1', ['step' => 1], ['companies' => $companies])
|
|
->with('projects', $projects);
|
|
}
|
|
|
|
// Se forem alterados dados dos Detalhes da Obra, vai ser alterado
|
|
public function EditprocessStep1(Request $request)
|
|
{
|
|
// Validação...
|
|
|
|
$project = CompanyProject::where('company_projects_id', $request->projectId)->first();
|
|
|
|
$project->company_project_description = $request->input('description_project');
|
|
$project->project_company_number = $request->input('project_company_number');
|
|
$project->project_company_responsible = $request->input('responsible_project_company');
|
|
$project->project_ispt_number = $request->input('n_project_ispt');
|
|
$project->project_ispt_responsible = $request->input('responsible_project_ispt');
|
|
|
|
//Verifica se exsite uma nova data, se existe atualiza o projecto com a nova, se nao existir usa a antiga
|
|
if ($request->date_started <> null) {
|
|
$project->date_started = $request->input('date_started');
|
|
} else {
|
|
$project->date_started = $request->input('date_started_present');
|
|
}
|
|
|
|
$project->save();
|
|
|
|
session(['form_data.step1' => $request->all()]);
|
|
|
|
return redirect()->route('articulated_2', ['id' => $project->company_projects_id])
|
|
->with('success', 'Detalhes do Project atualizados!');
|
|
}
|
|
|
|
public function removePendingEquipment($id)
|
|
{
|
|
$equipment = PendingEquipment::findOrFail($id);
|
|
$equipment->delete();
|
|
return back()->with('success', 'Equipamento pendente removido com sucesso!');
|
|
}
|
|
|
|
public function CreateNewEquipmentFromPendingEquipment(Request $request, $id)
|
|
{
|
|
$checkPendingEquipment = PendingEquipment::findOrFail($id);
|
|
|
|
// dd($checkPendingEquipment);
|
|
|
|
//Para que serve ??
|
|
$counter = 2;
|
|
$baseTag = $checkPendingEquipment->pending_equipment_tag;
|
|
$baseDescription = $checkPendingEquipment->pending_equipment_description;
|
|
|
|
// Ciclo para verificar se ja existe um equipamento com o mesmo nome se existir vai criando com o contador iniciado a partir de (2)
|
|
while (Equipment::where('equipment_tag', $baseTag . "({$counter})")->orWhere('equipment_description', $baseDescription . "({$counter})")->exists()) {
|
|
$counter++;
|
|
}
|
|
|
|
$newEquipment = new Equipment;
|
|
$newEquipment->unit_id = $checkPendingEquipment->pending_equipment_unit_id;
|
|
$newEquipment->equipment_type_id = $checkPendingEquipment->pending_equipment_type_id;
|
|
$newEquipment->equipment_tag = $baseTag . "({$counter})";
|
|
$newEquipment->equipment_description = $baseDescription . "({$counter})";
|
|
$newEquipment->equipment_serial_number = $checkPendingEquipment->pending_equipment_serial_number;
|
|
$newEquipment->equipment_brand = $checkPendingEquipment->pending_equipment_brand;
|
|
$newEquipment->equipment_model = $checkPendingEquipment->pending_equipment_model;
|
|
$newEquipment->company_projects_id = $checkPendingEquipment->pending_company_projects_id;
|
|
$newEquipment->save();
|
|
|
|
$newEquipmentWorkHistory = new EquipmentWorkHistory;
|
|
$newEquipmentWorkHistory->equipment_id = $newEquipment->equipment_id;
|
|
$newEquipmentWorkHistory->company_projects_id = $newEquipment->company_projects_id;
|
|
|
|
// Busca o maior ispt_number para o company_projects_id específico
|
|
$lastIsptNumber = EquipmentWorkHistory::where('company_projects_id', $newEquipment->company_projects_id)
|
|
->max('ispt_number');
|
|
|
|
// Se não houver registros, definimos o primeiro número para 1, caso contrário, incrementamos o último número encontrado
|
|
$newIsptNumber = $lastIsptNumber ? $lastIsptNumber + 1 : 1;
|
|
|
|
// Agora, atribuímos o novo número ISPT ao registro de histórico de equipamento
|
|
$newEquipmentWorkHistory->ispt_number = $newIsptNumber;
|
|
|
|
$newEquipmentWorkHistory->save();
|
|
|
|
|
|
$newEquipmentAssociationAmbits = new EquipmentAssociationAmbit;
|
|
$newEquipmentAssociationAmbits->equipmentWorkHistorys_id = $newEquipmentWorkHistory->equipmentWorkHistorys_id;
|
|
$newEquipmentAssociationAmbits->ambits_id = $request->EquipmentAmbit;
|
|
$newEquipmentAssociationAmbits->equipment_type_id = $checkPendingEquipment->pending_equipment_type_id;
|
|
$newEquipmentAssociationAmbits->save();
|
|
|
|
//Recebe a tabela com as associoacoes entre Âmbitos e tarefas Elementares
|
|
$TasksAssociationAmbits = TasksAssociationAmbits::all()->where('ambits_equipment_id', $newEquipmentAssociationAmbits->ambits_id);
|
|
|
|
foreach ($TasksAssociationAmbits as $TasksAssociationAmbit) {
|
|
$JoinsEquipmentsWithTasks = new OrderEquipmentTasks;
|
|
$JoinsEquipmentsWithTasks->equipmentWorkHistorys_id = $newEquipmentWorkHistory->equipmentWorkHistorys_id;
|
|
$JoinsEquipmentsWithTasks->execution_order = null;
|
|
$JoinsEquipmentsWithTasks->elemental_tasks_id = $TasksAssociationAmbit->elemental_tasks_id;
|
|
$JoinsEquipmentsWithTasks->further_tasks_id = null;
|
|
$JoinsEquipmentsWithTasks->inspection = 2;
|
|
$JoinsEquipmentsWithTasks->save();
|
|
}
|
|
|
|
|
|
$checkPendingEquipment->delete();
|
|
|
|
return back()->with('success', 'Equipamento ' . $newEquipment->equipment_tag . ' criado com sucesso');
|
|
}
|
|
|
|
|
|
public function processStep1(Request $request)
|
|
{
|
|
// dd($request);
|
|
//NAO DEVE SER CRIAR UMA NOVA EMPRESA NA CRIACAO DA OBRA (era uma boa ideia para facilitar ao Admin ter que criar a empresa para Depois a Obra, mas e necessario pelo facto da autentificao de 2 factores e envio e email , entao devido essa adicoes, nao preciso atualmente fazer sentido criar isto)
|
|
// Dito isto vamos sempre pensar que o Cliente ja deve estar criado , para ser feita uma Obra para o mesmo.
|
|
// dd($request);
|
|
// Validação...
|
|
|
|
if ($request->input('installation_id')) {
|
|
|
|
$installationId = $request->input('installation_id');
|
|
|
|
|
|
//Para criar uma nova instalacao
|
|
if ($installationId <> null && $installationId == 'new_install') {
|
|
|
|
// Criar uma nova instalação...
|
|
$newInstallation = new Plant;
|
|
|
|
$newInstallation->plant_name = $request->input('new_company_name');
|
|
$newInstallation->plant_address = $request->input('new_company_address');
|
|
$newInstallation->user_id = $request->input('user_id');
|
|
|
|
$newInstallation->save();
|
|
|
|
// Use o id da nova instalação.
|
|
$installationId = $newInstallation->plant_id;
|
|
|
|
// Verifica se há nomes de fábricas para criar
|
|
$factoryNames = $request->input('factoryNames', []);
|
|
|
|
foreach ($factoryNames as $factoryName) {
|
|
$newUnit = new Unit; // Supondo que `Unit` é o seu modelo para as fábricas
|
|
$newUnit->unit_name = $factoryName;
|
|
$newUnit->plant_id = $installationId; // ID da instalação criada anteriormente
|
|
$newUnit->save(); // Salva a nova fábrica no banco de dados
|
|
}
|
|
|
|
}
|
|
}
|
|
$receiveDetailsPlant = Plant::where('plant_id', $installationId)->first();
|
|
|
|
//Code apenas para criacao de Obra sem criar instlacao ou empresa
|
|
$project = new CompanyProject;
|
|
$project->company_project_description = $request->input('description_project');
|
|
$project->project_ispt_number = $request->input('n_project_ispt');
|
|
$project->project_company_number = $request->input('project_company_number');
|
|
$project->project_ispt_responsible = $request->input('responsible_project_ispt');
|
|
$project->project_company_responsible = $request->input('responsible_project_company');
|
|
$project->plant_id = $receiveDetailsPlant->plant_id;
|
|
$project->order_project = 1;
|
|
$project->date_started = $request->input('date_started');
|
|
|
|
$project->save();
|
|
|
|
return redirect()->route('articulated_2', ['id' => $project->company_projects_id])
|
|
->with('success', 'Project criado com sucesso!');
|
|
}
|
|
|
|
public function showStep2($company_projects_id)
|
|
{
|
|
$groupedArrayForPendingEquipments = session('groupedArrayForPendingEquipments');
|
|
// Verifique se a etapa 1 foi concluída
|
|
|
|
// if (!session('form_data.step1')) {
|
|
// return redirect('/createProject');
|
|
// }
|
|
|
|
//recebe o Id de Plant vai devolver todos os equipamentos relacionados a esta Instalação(plant)
|
|
// Carregue o projeto com o id fornecido
|
|
$project = CompanyProject::find($company_projects_id);
|
|
|
|
$numberProject = $project->company_projects_id;
|
|
|
|
$typeEquipments = EquipmentType::all();
|
|
|
|
//Retorna todas as Fabricas Unit, com base na Instalação
|
|
$checkUnits = DB::table('units')
|
|
->join('plants', 'units.plant_id', '=', 'plants.plant_id')
|
|
->join('company_projects', 'plants.plant_id', '=', 'company_projects.plant_id')
|
|
->select('units.*')
|
|
->where('company_projects.company_projects_id', '=', $company_projects_id)
|
|
->get();
|
|
|
|
//Retorna todos os Equipamentos, com base na instalcao do projecto
|
|
$checkEquipments = DB::table('equipments')
|
|
->join('units', 'equipments.unit_id', '=', 'units.unit_id')
|
|
->join('plants', 'units.plant_id', '=', 'plants.plant_id')
|
|
->select('equipments.*') // Seleciona todas as colunas da tabela 'equipments'
|
|
->where('plants.plant_id', '=', $project['plant_id']) // Filtra baseado no 'plant_id'
|
|
->get();
|
|
|
|
// Para listar os equipamentos vinculados na obra, buscamos suas associações gerais entre suas tabelas , ou seja a : fabrica(unit), tipo de equipamento e o Âmbito para se realizar a tarefas pretendida neste obra.
|
|
// $listEquipmentsProjects = Equipment::with(['unit', 'equipmentType', 'equipmentAssociationAmbit.ambitsEquipment'])
|
|
// ->where('company_projects_id', $company_projects_id)
|
|
// ->get();
|
|
|
|
$listEquipmentsProjects = Equipment::with([
|
|
'unit',
|
|
'equipmentType',
|
|
// 'equipmentAssociationAmbit.ambitsEquipment',
|
|
'specificAttributes' => function ($query) {
|
|
$query->orderBy('specific_attributes_value', 'asc');
|
|
}
|
|
])
|
|
->where('company_projects_id', $company_projects_id)
|
|
->get();
|
|
|
|
$pendingEquipments = PendingEquipment::where('pending_company_projects_id', $numberProject)->get();
|
|
|
|
if (!$pendingEquipments->isEmpty()) {
|
|
// Retornamos para a view 'step' => 2 indicando conclusao da primeira parte, $numberProject para associacao de equipamentos a esta obra, alem de todos os equipamentos e fabricao ja existente com base na Instalação que se iniciou a obra.
|
|
return view('projectsClients/articulated_2', ['step' => 2, 'numberProject' => $numberProject])
|
|
->with('danger', 'Equipamentos Pendentes: ' . count($pendingEquipments))
|
|
->with('pendingEquipments', $pendingEquipments)
|
|
->with('listEquipmentsProjects', $listEquipmentsProjects)
|
|
->with('typeEquipments', $typeEquipments)
|
|
->with('checkEquipments', $checkEquipments)
|
|
->with('checkUnits', $checkUnits)
|
|
->with('receiveNumberProject', $project)
|
|
->with('groupedArrayForPendingEquipments', $groupedArrayForPendingEquipments);
|
|
}
|
|
return view('projectsClients/articulated_2', ['step' => 2, 'numberProject' => $numberProject])
|
|
->with('listEquipmentsProjects', $listEquipmentsProjects)
|
|
->with('typeEquipments', $typeEquipments)
|
|
->with('checkEquipments', $checkEquipments)
|
|
->with('checkUnits', $checkUnits)
|
|
->with('groupedArrayForPendingEquipments', $groupedArrayForPendingEquipments)
|
|
->with('receiveNumberProject', $project);
|
|
}
|
|
|
|
public function createEquipmentManual(Request $request)
|
|
{
|
|
// EquipmentAmbit
|
|
// *** Recebe a Instalação(Plant), com base no número da Obra Criada
|
|
$receivePlant = DB::table('plants')
|
|
->join('company_projects', 'company_projects.plant_id', 'plants.plant_id')
|
|
->select('plants.plant_id')
|
|
->where('company_projects.company_projects_id', '=', $request->numberProject)
|
|
->get();
|
|
|
|
//recebe a lista de todos os equipmentos relacionados a obra que se esta a criar.
|
|
$listEquipmentsProjects = DB::table('equipments')
|
|
->select('equipments.*')
|
|
->where('equipments.company_projects_id', '=', $request->numberProject)
|
|
->get();
|
|
|
|
// Verifica se ja existe um equipamento com as as caracteristicas : tag,unit_id, iguais ao que pretendemos criar
|
|
$existingEquipment = Equipment::firstWhere([
|
|
'equipment_tag' => $request->tag,
|
|
'unit_id' => $request->unit_id
|
|
]);
|
|
|
|
if ($existingEquipment) {
|
|
return redirect()->route('articulated_2', ['id' => $request->numberProject])
|
|
->with('danger', 'Equipamento ja Existe !!')
|
|
->with('listEquipmentsProjects', $listEquipmentsProjects);
|
|
}
|
|
|
|
// Se realmente for um equipamento novo, verifica se ira associar a uma fabrica (unit) nova ou ja existente
|
|
$newEquipmentProject = new Equipment;
|
|
|
|
// Se for uma fabrica(Unit) existente
|
|
if ($request->new_unit_name == null) {
|
|
$newEquipmentProject->unit_id = $request->unit_id;
|
|
} else {
|
|
|
|
//ja retorna se for uma fabrica nova (Unit)
|
|
$newUnit = new Unit;
|
|
$newUnit->unit_name = $request->new_unit_name;
|
|
$newUnit->plant_id = $receivePlant[0]->plant_id;
|
|
$newUnit->save();
|
|
|
|
$newEquipmentProject->unit_id = $newUnit->unit_id;
|
|
}
|
|
|
|
$newEquipmentProject->equipment_type_id = $request->equipmentTypeId;
|
|
$newEquipmentProject->equipment_tag = $request->tag;
|
|
$newEquipmentProject->equipment_description = $request->equipmentDescription;
|
|
|
|
// Estes campos a baixo : podem ter valor ou não
|
|
$newEquipmentProject->equipment_serial_number = $request->serialNumberEquipment ?? NULL;
|
|
$newEquipmentProject->equipment_brand = $request->equipmentBrand ?? NULL;
|
|
$newEquipmentProject->equipment_model = $request->equipmentModel ?? NULL;
|
|
|
|
$newEquipmentProject->company_projects_id = $request->numberProject;
|
|
|
|
$newEquipmentProject->save();
|
|
|
|
// ID do equipamento criado
|
|
$equipmentID = $newEquipmentProject->equipment_id;
|
|
|
|
$newEquipmentWorkHistorys = new EquipmentWorkHistory;
|
|
|
|
// Verifica se já existem registros com o mesmo 'equipment_id' e 'company_projects_id'
|
|
$existingRecords = EquipmentWorkHistory::where('company_projects_id', $request->numberProject)
|
|
->orderBy('ispt_number', 'desc') // Ordena de forma decrescente
|
|
->first(); // Pega o primeiro resultado, que seria o maior número
|
|
|
|
if ($existingRecords) {
|
|
// Se existirem registros, o próximo número será o maior número existente + 1
|
|
$isptNumber = $existingRecords->ispt_number + 1;
|
|
} else {
|
|
// Se não existirem registros, começa com 1
|
|
$isptNumber = 1;
|
|
}
|
|
|
|
|
|
$newEquipmentWorkHistorys->equipment_id = $equipmentID;
|
|
$newEquipmentWorkHistorys->ispt_number = $isptNumber;
|
|
$newEquipmentWorkHistorys->company_projects_id = $request->numberProject;
|
|
|
|
$newEquipmentWorkHistorys->save();
|
|
|
|
$equipmentWorkHistorysID = $newEquipmentWorkHistorys->equipmentWorkHistorys_id;
|
|
|
|
// Verifica os campos do Card_do tipo de valvula selecionado (Ex: psv_card) e de acordo com os campos preenchidos se for de atributos especificos, ele compara o 'name' dos inputs com os 'general_attributes_equipment_description' da tabela : GeneralAttributesEquipment e associa
|
|
$checkAtributs = GeneralAttributesEquipment::whereIn('general_attributes_equipment_description', array_keys($request->all()))
|
|
->pluck('general_attributes_equipment_id', 'general_attributes_equipment_description')
|
|
->toArray();
|
|
|
|
// Recebe esta associacao, e cria um array para cada 'name'(inputs) igual ao 'general_attributes_equipment_description', contanto que seu valor(input) seja diferente de *NULL, assim o "$receivesAssociationAttributes" recebe o id de acordo com a tabela , o nome de acordo com a tabela e o valor do $request recebido associado ao campo
|
|
$receivesAssociationAttributes = [];
|
|
foreach ($checkAtributs as $description => $id) {
|
|
if ($request[$description] !== null) {
|
|
$receivesAssociationAttributes[] = [
|
|
'general_attributes_equipment_id' => $id,
|
|
'general_attributes_equipment_description' => $description,
|
|
'value' => $request[$description]
|
|
];
|
|
}
|
|
}
|
|
// Para cada um dos Arrays criados acima, vai criar os novos dados na tabela 'SpecificAttributesEquipmentType'
|
|
foreach ($receivesAssociationAttributes as $receivesAssociationAttribute) {
|
|
|
|
$AddAtributsEquipments = new SpecificAttributesEquipmentType;
|
|
$AddAtributsEquipments->equipment_id = $equipmentID;
|
|
$AddAtributsEquipments->equipment_type_id = $request->equipmentTypeId;
|
|
$AddAtributsEquipments->general_attributes_equipment_id = $receivesAssociationAttribute['general_attributes_equipment_id'];
|
|
$AddAtributsEquipments->specific_attributes_value = $receivesAssociationAttribute['value'];
|
|
|
|
$AddAtributsEquipments->save();
|
|
}
|
|
//Criar associacao do equipamento ao Âmbito
|
|
$AssociationEquipmentAmbit = new EquipmentAssociationAmbit;
|
|
$AssociationEquipmentAmbit->equipment_type_id = $request->equipmentTypeId;
|
|
$AssociationEquipmentAmbit->ambits_id = $request->EquipmentAmbit;
|
|
$AssociationEquipmentAmbit->equipmentWorkHistorys_id = $equipmentWorkHistorysID;
|
|
|
|
$AssociationEquipmentAmbit->save();
|
|
|
|
$execution_order = 1;
|
|
|
|
//Recebe a tabela com as associoacoes entre Âmbitos e tarefas Elementares
|
|
$TasksAssociationAmbits = TasksAssociationAmbits::all()->where('ambits_equipment_id', $AssociationEquipmentAmbit->ambits_id);
|
|
|
|
foreach ($TasksAssociationAmbits as $TasksAssociationAmbit) {
|
|
$JoinsEquipmentsWithTasks = new OrderEquipmentTasks;
|
|
$JoinsEquipmentsWithTasks->equipmentWorkHistorys_id = $equipmentWorkHistorysID;
|
|
$JoinsEquipmentsWithTasks->execution_order = $execution_order++;
|
|
$JoinsEquipmentsWithTasks->elemental_tasks_id = $TasksAssociationAmbit->elemental_tasks_id;
|
|
$JoinsEquipmentsWithTasks->further_tasks_id = null;
|
|
$JoinsEquipmentsWithTasks->inspection = 2;
|
|
$JoinsEquipmentsWithTasks->save();
|
|
}
|
|
|
|
// O $request->numberProject e sempre necessario retornar para indicar a obra que se esta modificando...
|
|
return redirect()->route('articulated_2', ['id' => $request->numberProject])
|
|
->with('success', 'Equipamento criado com sucesso')
|
|
->with('listEquipmentsProjects', $listEquipmentsProjects);
|
|
}
|
|
public function receiveIdEquipment(Equipment $equipment)
|
|
{
|
|
// return response()->json($equipment);
|
|
return view('projectsClients/articulated_2', ['equipment' => $equipment]);
|
|
}
|
|
|
|
public function processStep2(Request $request)
|
|
{
|
|
// Valide e processe os dados do formulário
|
|
$file = $request->file('documento');
|
|
// Recebe a id do Projecto criado
|
|
$company_projects_id = $request->numberProject;
|
|
// Inicializa o contador para ispt_number
|
|
$isptNumber = 1;
|
|
|
|
// Recebe o valor do campo 'chooseIfSelectOrCreateEquipments' do formulário
|
|
$chooseAction = $request->input('chooseIfSelectOrCreateEquipments');
|
|
|
|
// Certifique-se de que um arquivo foi enviado
|
|
if ($file) {
|
|
//Busca o nome do arquivo xslx.
|
|
$originalFileName = $file->getClientOriginalName();
|
|
// Carregue o arquivo Excel
|
|
$spreadsheet = IOFactory::load($file->path());
|
|
// Obtenha a primeira planilha, onde fica os nomes chaves para associar as tabelas : 'general_attributes_equipaments' ,'equipments' e 'equipmentWorkHistorys'
|
|
$worksheet = $spreadsheet->getSheet(0);
|
|
// Transforme os dados da planilha em um array
|
|
$data = $worksheet->toArray();
|
|
|
|
// Retorna um array com todos os names preenchidos na primeira linha do template de Excel
|
|
$columnNames = $data[0];
|
|
$countPendingEquipments = 0;
|
|
$countEquipment = 0;
|
|
|
|
// Recebo os nomes das colunas do execel dependendo da linguagem selecionada
|
|
$columnRealNames = $data[5];
|
|
|
|
$equipmentPendingLogs = [];
|
|
$ignoredLines = [];
|
|
|
|
// Comece a partir da sexta linha do template os dados dos Equipamentos
|
|
for ($i = 6; $i < count($data); $i++) {
|
|
|
|
$dataLines = $data[$i];
|
|
|
|
// Verifica se a coluna 'fábrica' (primeiro campo) está vazia
|
|
if (empty($dataLines[0])) {
|
|
// Se a coluna 'fábrica' estiver vazia, pule para a próxima linha
|
|
continue;
|
|
}
|
|
$emptyFields = [];
|
|
|
|
// Verifica se os 5 primeiros campos essenciais estão preenchidos
|
|
for ($j = 0; $j < 5; $j++) {
|
|
if (empty($dataLines[$j])) {
|
|
// Adiciona o índice do campo vazio ao array $camposVazios
|
|
$emptyFields[] = $columnRealNames[$j]; // ou simplesmente $j se não tiver o nome da coluna
|
|
}
|
|
}
|
|
|
|
|
|
|
|
// Em cada um das linhas horizontais do excel, vai se guardar a 'key' vinculada ao valor do campo preenchido ou seja a 'key' vai ter o mesmo nome de um dos dados da tabela 'general_attributes_equipaments' na coluna : general_attributes_equipment_description, assim sendo mais facil implementar na tabela : specific_attributes_equipament_types
|
|
$joinArrays = array_combine($columnNames, $dataLines);
|
|
|
|
// vai guardar todos os campos de possiveis novos equipamentos, cada um em um array para multiplos inserts, na base de dados
|
|
$datas = array_filter($joinArrays, function ($chave) {
|
|
return !empty($chave);
|
|
}, ARRAY_FILTER_USE_KEY);
|
|
|
|
//Indentifica qual o tipo de equipamento selecionado de acordo com a tabela EquipmentType
|
|
$equipmentType = EquipmentType::where('equipment_type_name', $datas['equipment_type_name'])->first();
|
|
|
|
$checkFactory = Unit::where('unit_name', $datas['unit'])->first();
|
|
|
|
// Antes de criar o novo equipamento, verifique se já existe um equipamento
|
|
// com o mesmo factory_id e tag.
|
|
$existingEquipment = Equipment::where('unit_id', $checkFactory->unit_id)
|
|
->where('equipment_tag', $datas['equipment_tag'])
|
|
->first();
|
|
|
|
//Nesta para vamos separar como tratar os equipamentos que existem, dependendo do tipo de select que o utilizador utilizou
|
|
|
|
if ($chooseAction == 'selectEquipments') {
|
|
|
|
|
|
|
|
if ($existingEquipment) {
|
|
|
|
$foundInExcel = false;
|
|
$rowExcelDuplicated = null;
|
|
|
|
// Verificar duplicatas no Excel
|
|
for ($j = 6; $j < $i; $j++) {
|
|
if ($data[$j][0] === $datas['unit'] && $data[$j][1] === $datas['equipment_tag'] && $data[$j][4] === $datas['equipment_description']) {
|
|
$foundInExcel = true;
|
|
$rowExcelDuplicated = $j;
|
|
break;
|
|
}
|
|
}
|
|
|
|
// Associar o equipamento encontrado ao projeto
|
|
$existingEquipment->company_projects_id = $company_projects_id;
|
|
$existingEquipment->save();
|
|
|
|
$countEquipment++;
|
|
|
|
// Guardo os valores de 'id' e do 'tipo de equipamento' que nosso novo equipamento acabado de criar
|
|
$receveEquipment_ID = $existingEquipment->equipment_id;
|
|
$receveEquipament_type_ID = $existingEquipment->equipment_type_id;
|
|
|
|
|
|
|
|
// Verifica se já existem registros com o mesmo 'equipment_id' e 'company_projects_id'
|
|
$existingRecords = EquipmentWorkHistory::where('company_projects_id', $company_projects_id)
|
|
->orderBy('ispt_number', 'desc') // Ordena de forma decrescente
|
|
->first(); // Pega o primeiro resultado, que seria o maior número
|
|
|
|
|
|
if ($existingRecords) {
|
|
// Se existirem registros, o próximo número será o maior número existente + 1
|
|
$isptNumber = $existingRecords->ispt_number + 1;
|
|
} else {
|
|
// Se não existirem registros, começa com 1
|
|
$isptNumber = 1;
|
|
}
|
|
|
|
$newEquipmentWorkHistory = new EquipmentWorkHistory;
|
|
|
|
$newEquipmentWorkHistory->equipment_id = $receveEquipment_ID;
|
|
$newEquipmentWorkHistory->company_projects_id = $company_projects_id;
|
|
// Continua com o processo de salvar o novo registro
|
|
$newEquipmentWorkHistory->ispt_number = $isptNumber;
|
|
|
|
|
|
|
|
$newEquipmentWorkHistory->save();
|
|
|
|
// Recebe o Id do 'EquipmentWorkHistory' criado.
|
|
$recebeNewEquipmentWorkHistoryID = $newEquipmentWorkHistory->equipmentWorkHistorys_id;
|
|
|
|
$isptNumber++;
|
|
|
|
|
|
$ambit = AmbitsEquipment::where('ambits_description', $datas['ambit'])->first();
|
|
|
|
if ($ambit) {
|
|
$ambit_id = $ambit->ambits_id;
|
|
}
|
|
|
|
//Criar associacao do equipamento ao Âmbito
|
|
$AssociationEquipmentAmbit = new EquipmentAssociationAmbit;
|
|
$AssociationEquipmentAmbit->equipment_type_id = $existingEquipment->equipment_type_id;
|
|
$AssociationEquipmentAmbit->ambits_id = $ambit_id;
|
|
$AssociationEquipmentAmbit->equipmentWorkHistorys_id = $newEquipmentWorkHistory->equipmentWorkHistorys_id;
|
|
|
|
$AssociationEquipmentAmbit->save();
|
|
|
|
//Recebe a tabela com as associoacoes entre Âmbitos e tarefas Elementares
|
|
$TasksAssociationAmbits = TasksAssociationAmbits::all()->where('ambits_equipment_id', $AssociationEquipmentAmbit->ambits_id);
|
|
|
|
foreach ($TasksAssociationAmbits as $TasksAssociationAmbit) {
|
|
$JoinsEquipmentsWithTasks = new OrderEquipmentTasks;
|
|
$JoinsEquipmentsWithTasks->equipmentWorkHistorys_id = $newEquipmentWorkHistory->equipmentWorkHistorys_id;
|
|
$JoinsEquipmentsWithTasks->elemental_tasks_id = $TasksAssociationAmbit->elemental_tasks_id;
|
|
$JoinsEquipmentsWithTasks->further_tasks_id = null;
|
|
$JoinsEquipmentsWithTasks->save();
|
|
}
|
|
|
|
// Separa o nome do arquivo para obter o tipo de documento e a data-hora
|
|
$parts = explode('_', $originalFileName);
|
|
$documentType = $parts[2]; // 98
|
|
$timestamp = $parts[3]; // 2024-01-14_14-33
|
|
|
|
// Cria um array agrupado
|
|
$groupedArrayForPendingEquipments = [$documentType, [$timestamp, $equipmentPendingLogs]];
|
|
}
|
|
//Se nao existir deve retornar 'equipamentos nao encontrados, deve ser a mesma coisa que as linha ignoradas
|
|
$ignoredLines[] = [
|
|
'line' => $i + 1,
|
|
'emptyFields' => ['Nenhum equipamento foi localizado que cumpra os requisitos especificados nesta linha.']
|
|
];
|
|
continue; // Pula para a próxima linha
|
|
|
|
|
|
} elseif ($chooseAction == 'createEquipments') {
|
|
|
|
if (!empty($emptyFields)) {
|
|
// Se houver campos vazios, adicione a linha e os campos vazios às linhas ignoradas
|
|
$ignoredLines[] = [
|
|
'line' => $i + 1,
|
|
'emptyFields' => $emptyFields
|
|
];
|
|
continue; // Pula para a próxima linha
|
|
}
|
|
|
|
if ($existingEquipment) {
|
|
|
|
$foundInExcel = false;
|
|
$rowExcelDuplicated = null;
|
|
|
|
// Verificar duplicatas no Excel
|
|
for ($j = 6; $j < $i; $j++) {
|
|
if ($data[$j][0] === $datas['unit'] && $data[$j][1] === $datas['equipment_tag'] && $data[$j][4] === $datas['equipment_description']) {
|
|
$foundInExcel = true;
|
|
$rowExcelDuplicated = $j;
|
|
break;
|
|
}
|
|
}
|
|
|
|
// Se o equipamento existir, crie o novo equipamento na tabela pending_equipaments.
|
|
$pendingEquipament = new PendingEquipment;
|
|
|
|
// Defina os atributos do pendingEquipament conforme necessário.
|
|
$pendingEquipament->pending_equipment_unit_id = $checkFactory->unit_id;
|
|
$pendingEquipament->pending_equipment_type_id = $equipmentType->equipment_type_id;
|
|
$pendingEquipament->pending_equipment_tag = $datas['equipment_tag'];
|
|
$pendingEquipament->pending_equipment_description = $datas['equipment_description'];
|
|
$pendingEquipament->pending_equipment_serial_number = $datas['serial_number'];
|
|
$pendingEquipament->pending_equipment_brand = $datas['model'];
|
|
$pendingEquipament->pending_company_projects_id = $company_projects_id;
|
|
$pendingEquipament->save();
|
|
|
|
// Incremente o contador de PendingEquipments
|
|
$countPendingEquipments++;
|
|
|
|
// A variavel $pendenteLogs, na 'linhaExcel' vai recebe a linha do execel onde encontrou a duplicata em Array, vinda do primeiro $data, onde transforma toda o execel em array
|
|
// 'existingEquipmentId' vai ver qual o id do equipament que esta sendo duplicado.
|
|
//'duplicadoNoExcel' vai ser um boolean indicando que este valor duplicado veio da base de dados ou se foi de uma coluna anterior.
|
|
// linhaExcelDuplicada se o valor de duplicadoNoExcel for 'true' quer dizer que existe uma linha anterior com o mesmos dados, e essa variavel busco a o numero do array desta linha com base na variavel primeiro $data
|
|
$equipmentPendingLogs[] = [
|
|
'rowExecel' => $i + 1,
|
|
'pendingEquipmentId' => $pendingEquipament->pending_equipment_id,
|
|
'existingEquipmentId' => $existingEquipment->equipment_id,
|
|
'foundInExcel' => $foundInExcel,
|
|
'rowExcelDuplicated' => $rowExcelDuplicated
|
|
];
|
|
|
|
// Continue com o próximo loop.
|
|
continue;
|
|
}
|
|
|
|
$newEquipament = new Equipment;
|
|
|
|
$newEquipament->unit_id = $checkFactory->unit_id;
|
|
$newEquipament->equipment_type_id = $equipmentType->equipment_type_id;
|
|
$newEquipament->equipment_Description = $datas['equipment_description'];
|
|
$newEquipament->equipment_tag = $datas['equipment_tag'];
|
|
$newEquipament->equipment_serial_number = $datas['serial_number'];
|
|
$newEquipament->equipment_brand = $datas['brand'];
|
|
$newEquipament->equipment_model = $datas['model'];
|
|
$newEquipament->company_projects_id = $company_projects_id;
|
|
|
|
$newEquipament->save();
|
|
|
|
$countEquipment++;
|
|
|
|
// Guardo os valores de 'id' e do 'tipo de equipamento' que nosso novo equipamento acabado de criar
|
|
$receveEquipment_ID = $newEquipament->equipment_id;
|
|
$receveEquipament_type_ID = $newEquipament->equipment_type_id;
|
|
|
|
|
|
// Verifica se já existem registros com o mesmo 'equipment_id' e 'company_projects_id'
|
|
$existingRecords = EquipmentWorkHistory::where('company_projects_id', $company_projects_id)
|
|
->orderBy('ispt_number', 'desc') // Ordena de forma decrescente
|
|
->first(); // Pega o primeiro resultado, que seria o maior número
|
|
|
|
|
|
if ($existingRecords) {
|
|
// Se existirem registros, o próximo número será o maior número existente + 1
|
|
$isptNumber = $existingRecords->ispt_number + 1;
|
|
} else {
|
|
// Se não existirem registros, começa com 1
|
|
$isptNumber = 1;
|
|
}
|
|
|
|
$newEquipmentWorkHistory = new EquipmentWorkHistory;
|
|
|
|
$newEquipmentWorkHistory->equipment_id = $receveEquipment_ID;
|
|
$newEquipmentWorkHistory->ispt_number = $isptNumber;
|
|
$newEquipmentWorkHistory->company_projects_id = $company_projects_id;
|
|
|
|
$newEquipmentWorkHistory->save();
|
|
|
|
// Recebe o Id do 'EquipmentWorkHistory' criado.
|
|
$recebeNewEquipmentWorkHistoryID = $newEquipmentWorkHistory->equipmentWorkHistorys_id;
|
|
|
|
$isptNumber++;
|
|
|
|
$ambit = AmbitsEquipment::where('ambits_description', $datas['ambit'])->first();
|
|
|
|
if ($ambit) {
|
|
$ambit_id = $ambit->ambits_id;
|
|
}
|
|
|
|
//Criar associacao do equipamento ao Âmbito
|
|
$AssociationEquipmentAmbit = new EquipmentAssociationAmbit;
|
|
$AssociationEquipmentAmbit->equipment_type_id = $newEquipament->equipment_type_id;
|
|
$AssociationEquipmentAmbit->ambits_id = $ambit_id;
|
|
$AssociationEquipmentAmbit->equipmentWorkHistorys_id = $newEquipmentWorkHistory->equipmentWorkHistorys_id;
|
|
|
|
$AssociationEquipmentAmbit->save();
|
|
|
|
//Recebe a tabela com as associoacoes entre Âmbitos e tarefas Elementares
|
|
$TasksAssociationAmbits = TasksAssociationAmbits::all()->where('ambits_equipment_id', $AssociationEquipmentAmbit->ambits_id);
|
|
|
|
foreach ($TasksAssociationAmbits as $TasksAssociationAmbit) {
|
|
$JoinsEquipmentsWithTasks = new OrderEquipmentTasks;
|
|
$JoinsEquipmentsWithTasks->equipmentWorkHistorys_id = $newEquipmentWorkHistory->equipmentWorkHistorys_id;
|
|
$JoinsEquipmentsWithTasks->elemental_tasks_id = $TasksAssociationAmbit->elemental_tasks_id;
|
|
$JoinsEquipmentsWithTasks->further_tasks_id = null;
|
|
$JoinsEquipmentsWithTasks->save();
|
|
}
|
|
|
|
// Separa o nome do arquivo para obter o tipo de documento e a data-hora
|
|
$parts = explode('_', $originalFileName);
|
|
$documentType = $parts[2]; // 98
|
|
$timestamp = $parts[3]; // 2024-01-14_14-33
|
|
|
|
// Cria um array agrupado
|
|
$groupedArrayForPendingEquipments = [$documentType, [$timestamp, $equipmentPendingLogs]];
|
|
// Armazenar $groupedArrayForPendingEquipments na sessão
|
|
session(['groupedArrayForPendingEquipments' => $groupedArrayForPendingEquipments]);
|
|
$pendingEquipments = PendingEquipment::where('pending_company_projects_id', $request->numberProject)->get();
|
|
|
|
}
|
|
}
|
|
|
|
if ($countPendingEquipments != 0 && !empty($equipmentPendingLogs)) {
|
|
// Se houver equipamentos pendentes, redirecione com essa informação e inclua os $linhasIgnoradas se não estiverem vazios
|
|
return redirect()->route('articulated_2', ['id' => $request->numberProject])
|
|
->with('danger', 'Equipamentos Pendentes criados: ' . $countPendingEquipments)
|
|
->with('dangerLogs', $ignoredLines)
|
|
->with('equipmentPendingLogs', $equipmentPendingLogs)
|
|
->with('pendingEquipments', $pendingEquipments);
|
|
} else {
|
|
// Se não houver equipamentos pendentes, redirecione com uma mensagem de sucesso e inclua os $linhasIgnoradas se não estiverem vazios
|
|
return redirect()->route('articulated_2', ['id' => $request->numberProject])
|
|
->with('success', 'Equipamentos Criados: ' . $countEquipment)
|
|
->with('dangerLogs', $ignoredLines);
|
|
}
|
|
// return redirect()->route('articulated_2', ['id' => $request->numberProject])
|
|
// ->with('success', 'Equipamentos Adicionados a Obra com sucesso: ' . $countEquipment);
|
|
}
|
|
//Nao chega aqui ainda pois volta para a pagina com dados ja carregados.
|
|
|
|
session(['form_data.step2' => $request->all()]);
|
|
|
|
// Redirecione o Utilizador para a próxima etapa
|
|
return redirect('/workStation_3');
|
|
}
|
|
|
|
public function showStep3($company_projects_id)
|
|
{
|
|
$equipments = Equipment::where('company_projects_id', $company_projects_id)
|
|
->get();
|
|
|
|
foreach ($equipments as $equipment) {
|
|
$tags = [];
|
|
// Se for psv tem o id 3 e atualmente sao os unicos tipos de valvulas que tem obturador (cv),(isv) nao apresentam.
|
|
if ($equipment->equipment_type_id == 3) {
|
|
$tags = ['@Corpo', '@Flange', '@Obturador'];
|
|
} else {
|
|
$tags = ['@Corpo', '@Flange'];
|
|
}
|
|
|
|
|
|
foreach ($tags as $tag) {
|
|
$associatedEquipment = QrcodesAssociatedEquipment::where('equipment_id', $equipment->equipment_id)
|
|
->where('component_tag', 'LIKE', '%' . $tag)
|
|
->first();
|
|
|
|
if ($associatedEquipment) {
|
|
// Atualizar a coluna component_tag para ser igual à equipment_tag, mantendo a parte após o "@"
|
|
$newComponentTag = $equipment->equipment_tag . $tag;
|
|
$associatedEquipment->component_tag = $newComponentTag;
|
|
$associatedEquipment->save();
|
|
} else {
|
|
// Criar uma nova entrada
|
|
QrcodesAssociatedEquipment::create([
|
|
'equipment_id' => $equipment->equipment_id,
|
|
'component_tag' => $equipment->equipment_tag . $tag
|
|
]);
|
|
}
|
|
}
|
|
}
|
|
|
|
// Obter IDs de equipamentos ativos do projeto especificado.
|
|
$activeEquipmentIds = Equipment::where('company_projects_id', $company_projects_id)
|
|
->pluck('equipment_id')
|
|
->toArray();
|
|
|
|
// Identificar todos os equipment_id em QrcodesAssociatedEquipment.
|
|
$equipmentIdsInQrcodes = QrcodesAssociatedEquipment::pluck('equipment_id')->unique()->toArray();
|
|
|
|
// Verificar quais desses equipment_id foram desassociados de qualquer projeto na tabela Equipment.
|
|
$orphanEquipmentIds = Equipment::whereIn('equipment_id', $equipmentIdsInQrcodes)
|
|
->whereNull('company_projects_id')
|
|
->pluck('equipment_id')
|
|
->toArray();
|
|
|
|
// Excluir todas as entradas em QrcodesAssociatedEquipment para os equipment_id desassociados.
|
|
foreach ($orphanEquipmentIds as $orphanId) {
|
|
QrcodesAssociatedEquipment::where('equipment_id', $orphanId)->delete();
|
|
}
|
|
|
|
//Sempre que entrar na view ja verifica se existe 'Workstations' preparadas para esta obra.
|
|
$listWorkstations = ConstructionWorkstation::where('company_projects_id', $company_projects_id)->get();
|
|
|
|
$futherTasks = FurtherTasks::where('company_projects_id', $company_projects_id)
|
|
->get();
|
|
|
|
return view('projectsClients/workStation_3', ['step' => 3, 'numberProject' => $company_projects_id])
|
|
->with('listWorkstations', $listWorkstations)
|
|
->with('equipments', $equipments)
|
|
->with('futherTasks', $futherTasks);
|
|
}
|
|
|
|
public function workstationsAssociationTasks(Request $request)
|
|
{
|
|
$workStation = ConstructionWorkstation::where('id_workstations', $request->idWorkStation)->first();
|
|
|
|
// Trocar o nome se for diferente do recebido
|
|
if ($workStation) {
|
|
$workStation->nomenclature_workstation = $request->nameWorkstation;
|
|
$workStation->save();
|
|
}
|
|
|
|
// Atualizar a lista de tipos de tarefas para incluir os novos grupos
|
|
$taskTypes = ['generalTasks', '1', '2', '3', 'FurtherTasks'];
|
|
|
|
foreach ($taskTypes as $groupTasks) {
|
|
if (isset($request[$groupTasks])) { // Checar se esse grupo de tarefas existe no request
|
|
foreach ($request[$groupTasks] as $taskID => $check) {
|
|
|
|
if ($groupTasks == 'FurtherTasks') {
|
|
// Encontra a tarefa existente, se houver, para FurtherTasks
|
|
$taskAssociation = WorkstationsAssociationTasks::where('id_workstations', $workStation->id_workstations)
|
|
->where('further_tasks_id', $taskID)
|
|
->where('company_projects_id', $workStation->company_projects_id)
|
|
->first();
|
|
} else {
|
|
// Encontra a tarefa existente, se houver, para os outros grupos
|
|
$taskAssociation = WorkstationsAssociationTasks::where('id_workstations', $workStation->id_workstations)
|
|
->where('elemental_tasks_id', $taskID)
|
|
->where('company_projects_id', $workStation->company_projects_id)
|
|
->first();
|
|
}
|
|
|
|
if ($check == 'on') {
|
|
if (!$taskAssociation) {
|
|
$taskAssociation = new WorkstationsAssociationTasks;
|
|
$taskAssociation->id_workstations = $workStation->id_workstations;
|
|
if ($groupTasks == 'FurtherTasks') {
|
|
$taskAssociation->further_tasks_id = $taskID; // Usando $taskID, que é a key
|
|
} else {
|
|
$taskAssociation->elemental_tasks_id = $taskID; // Usando $taskID, que é a key
|
|
}
|
|
$taskAssociation->company_projects_id = $workStation->company_projects_id;
|
|
}
|
|
$taskAssociation->save();
|
|
} elseif ($check == 'off' && $taskAssociation) {
|
|
$taskAssociation->delete();
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
|
|
// Redirecionar de volta com uma mensagem de sucesso
|
|
return back()->with('success', 'Posto de trabalho : ' . $workStation->name_workstations . ' atualizado com sucesso!');
|
|
}
|
|
|
|
public function processStep3(Request $request)
|
|
{
|
|
// Valide e processe os dados do formulário
|
|
// ...
|
|
session(['form_data.step3' => $request->all()]);
|
|
|
|
// Aqui, todas as etapas foram concluídas
|
|
// Você pode redirecionar o Utilizador para uma página de "Obrigado" ou processar os dados do formulário
|
|
// ...
|
|
}
|
|
|
|
public function index()
|
|
{
|
|
|
|
|
|
$results = DB::table('equipments')
|
|
->join('specific_attributes_equipament_types', 'equipments.equipment_id', '=', 'specific_attributes_equipament_types.equipment_id')
|
|
->join('general_attributes_equipaments', 'specific_attributes_equipament_types.specific_attributes_equipment_type_id', '=', 'general_attributes_equipaments.general_attributes_equipment_id')
|
|
->select('equipments.equipment_tag', 'general_attributes_equipaments.general_attributes_equipment_description', 'specific_attributes_equipament_types.specific_attributes_value')
|
|
->get();
|
|
|
|
|
|
// dd($results);
|
|
|
|
$groupedEquipments = [];
|
|
|
|
foreach ($results as $result) {
|
|
if (!isset($groupedEquipments[$result->tag])) {
|
|
$groupedEquipments[$result->tag] = [];
|
|
}
|
|
|
|
$groupedEquipments[$result->tag][] = [
|
|
'description' => $result->description,
|
|
'value' => $result->value
|
|
];
|
|
}
|
|
|
|
$equipments = DB::table('equipments')->get();
|
|
|
|
foreach ($equipments as $equipment) {
|
|
if (isset($groupedEquipments[$equipment->tag])) {
|
|
$equipment->specific_attributes = $groupedEquipments[$equipment->tag];
|
|
}
|
|
}
|
|
$allPossibleAttributes = GeneralAttributesEquipment::all()->pluck('description')->toArray();
|
|
|
|
return view('articulated_2', ['equipments' => $equipments, 'allAttributes' => $allPossibleAttributes]);
|
|
// Retorne a view com os dados
|
|
// return view('test', ['equipments' => $equipments]);
|
|
}
|
|
|
|
|
|
public function listCompanies()
|
|
{
|
|
$companies = User::where('type_users', 3)->get();
|
|
return view('projectsClients/createProject', ['companies' => $companies]);
|
|
}
|
|
|
|
|
|
public function createProject(Request $request)
|
|
{
|
|
|
|
// Validação...
|
|
$installationId = $request->input('installation_id');
|
|
|
|
if ($installationId == 'new_install') {
|
|
// Criar uma nova instalação...
|
|
$newInstallation = new Unit;
|
|
$newInstallation->installation_name = $request->input('new_company_name');
|
|
$newInstallation->address = $request->input('new_company_address');
|
|
$newInstallation->user_id = $request->input('user_id');
|
|
|
|
$newInstallation->save();
|
|
|
|
// Use o id da nova instalação.
|
|
$installationId = $newInstallation->id;
|
|
// dd($installationId);
|
|
}
|
|
|
|
$project = new CompanyProject;
|
|
|
|
$project->description_project = $request->input('description_project');
|
|
$project->n_project_ispt = $request->input('n_project_ispt');
|
|
$project->responsible_project_ispt = $request->input('responsible_project_ispt');
|
|
$project->responsible_project_company = $request->input('responsible_project_company');
|
|
$project->date_started = $request->input('date_started');
|
|
|
|
$project->installation_id = $installationId;
|
|
|
|
$project->save();
|
|
|
|
return redirect()->route('createProject')->with('success', 'Dados guardados com sucesso');
|
|
// return redirect()->route('createProject')->with('success', 'Dados guardados com sucesso');
|
|
|
|
}
|
|
|
|
public function storeProject(Request $request)
|
|
{
|
|
if ($request->input('company_id') == 'new') {
|
|
$company = new CompanyProject; // Substitua "Company" pelo nome do seu modelo de empresas
|
|
$company->name = $request->input('new_company_name');
|
|
$company->save();
|
|
|
|
$company_id = $company->id;
|
|
} else {
|
|
$company_id = $request->input('company_id');
|
|
}
|
|
|
|
// Agora, você pode usar $company_id ao criar o projeto
|
|
}
|
|
|
|
public function getByUserNif(Request $request)
|
|
{
|
|
|
|
// dd(Plant::where('user_id', $request->input('user_id'))->get());
|
|
|
|
$user_id = $request->input('user_id'); //Check
|
|
$installations = Plant::where('user_id', $user_id)->get();
|
|
|
|
return response()->json($installations);
|
|
}
|
|
|
|
public function getAmbits($equipmentType)
|
|
{
|
|
|
|
$ambits = DB::table('ambits_equipments')
|
|
->select('ambits_equipments.*')
|
|
->where('ambits_equipments.equipment_type_id', $equipmentType)
|
|
->get();
|
|
return response()->json($ambits);
|
|
}
|
|
|
|
public function getAttributes($id)
|
|
{
|
|
$equipment = Equipment::with('specificAttributes')->find($id);
|
|
return response()->json($equipment->specificAttributes);
|
|
}
|
|
}
|