diff --git a/app/Http/Controllers/CreateProjectController copy.php b/app/Http/Controllers/CreateProjectController copy.php new file mode 100755 index 00000000..ea10f0e0 --- /dev/null +++ b/app/Http/Controllers/CreateProjectController copy.php @@ -0,0 +1,1525 @@ +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(); + + + // *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->equipment_id = $equipmentId; + $newOrderEquipmentTask->execution_order = $insertPosition; + $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) + { + // dd($request); + + foreach ($request->equipment as $equipment) { + $equipmentModel = Equipment::where('equipment_id', $equipment['equipment_id'])->first(); + + if ($equipmentModel) { + $equipmentModel->company_projects_id = $request->receiveNumberProject; + $equipmentModel->save(); + } + } + return redirect()->back()->with('success', 'Equipametos associados a Obra com Sucesso !'); + } + + public function receiveUnitsForExcelTemplate($numberProject) + { + $receveCompanyProject = CompanyProject::where('company_projects_id', $numberProject)->first(); + $recevePlant = Plant::where('plant_id', $receveCompanyProject->plant_id)->first(); + $receveUnits = Unit::where('plant_id', $recevePlant->plant_id)->get(); + $filePath = public_path('templateExcel/TestTemplate.xlsx'); + // Load the spreadsheet + $spreadsheet = IOFactory::load($filePath); + // Get the second sheet + $sheet = $spreadsheet->getSheet(1); // Sheet index starts from 0 + $row = 1; // Row number where you want to start inserting data + foreach ($receveUnits as $unit) { + // Set value for column D + $sheet->setCellValue('D' . $row, $unit->unit_name); + $row++; + } + // Generate and return the download response + return $this->createDownloadResponse($spreadsheet, 'Valves_Template.xlsx'); + } + + 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 EditEquipmentsProjects(Request $request) + { + // dd($request); + // Localiza o equipment pelo numberProject + $equipment = Equipment::find($request->equipmentId); + + // Atualiza os campos + $equipment->equipment_tag = $request->tag; + $equipment->equipment_description = $request->equipmentDescription; + $equipment->equipment_serial_number = $request->serialNumberEquipment; + $equipment->equipment_brand = $request->equipmentBrand; + $equipment->equipment_model = $request->equipmentModel; + + $equipment->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', $request->equipmentId) + ->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', $request->equipmentId) + ->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 = $request->equipmentId; + $specificAttributes->equipment_type_id = $equipment->equipment_type_id; + $specificAttributes->general_attributes_equipment_id = $key; + $specificAttributes->specific_attributes_value = $value; + $specificAttributes->save(); + } + } + } + } + + + // 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) { + $orderEquipmentTask = new OrderEquipmentTasks(); + $orderEquipmentTask->equipment_id = $request->equipmentId; + $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('equipment_id', $request->equipmentId) + ->orderBy('execution_order', 'asc') + ->get(); + + foreach ($remainingOrderEquipmentTasks as $orderEquipmentTask) { + $orderEquipmentTask->execution_order = $executionOrder; + $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('test2', ['id' => $request->numberProject]) + ->with('success', 'Equipamento ' . $equipment->equipment_tag . ' Editado com Sucesso!!!') + ->with('taskExecutionOrders', $taskExecutionOrders); + } + + 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('test3', ['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(); + + 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) + { + } + + 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); + + $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(); + + $receiveEquipmentID = $newEquipment->equipment_id; + + $newEquipmentAssociationAmbits = new EquipmentAssociationAmbit; + $newEquipmentAssociationAmbits->equipment_type_id = $newEquipment->equipment_type_id; + $newEquipmentAssociationAmbits->ambits_id = $request->EquipmentAmbit; + $newEquipmentAssociationAmbits->equipment_id = $receiveEquipmentID; + $newEquipmentAssociationAmbits->save(); + + + + $checkPendingEquipment->delete(); + + return back()->with('success', 'Equipamento ' . $newEquipment->equipment_tag . ' criado com sucesso'); + } + + + public function processStep1(Request $request) + { + // Validação... + $installationId = $request->input('installation_id'); + + if ($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; + } + + $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'); + + // Verifica se e igual a nulo , se for usa a data ja existente + if ($request->date_started === null) { + $project->date_started = $request->input('date_started_present'); + } else + $project->date_started = $request->input('date_started'); + + $project->plant_id = $installationId; + $project->order_project = 1; + + $project->save(); + + session(['form_data.step1' => $request->all()]); + + // // Redirecione o Utilizador para a próxima etapa + // return redirect('/test2') + // ->with('project', $project) + // ->with('success', 'Dados guardados com sucesso'); + return redirect()->route('test2', ['id' => $project->company_projects_id]) + ->with('success', 'Detalhes, Projecto criado com sucesso'); + } + + public function showStep2($company_projects_id) + { + // 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', + 'specificAttributes' => function ($query) { + $query->orderBy('specific_attributes_value', 'asc'); + } + ]) + ->where('company_projects_id', $company_projects_id) + ->get(); + + dd($listEquipmentsProjects); + + $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); + } + return view('projectsClients/articulated_2', ['step' => 2, 'numberProject' => $numberProject]) + ->with('listEquipmentsProjects', $listEquipmentsProjects) + ->with('typeEquipments', $typeEquipments) + ->with('checkEquipments', $checkEquipments) + ->with('checkUnits', $checkUnits) + ->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('test2', ['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; + + $newEquipmentWorkHistorys->equipment_id = $equipmentID; + $newEquipmentWorkHistorys->ispt_number = 0; + $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('test2', ['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; + + // Certifique-se de que um arquivo foi enviado + if ($file) { + // 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 + $nomesColunas = $data[0]; + + // dd($data); + + $countPendingEquipments = 0; + $countNewEquipment = 0; + + $linhasIgnoradas = []; + + // Comece a partir da sexta linha do template os dados dos Equipamentos + for ($i = 6; $i < count($data); $i++) { + + $dadosLinha = $data[$i]; + + // Verifica se os 5 primeiros campos essenciais estao preenchidos, um deles não estiver preenchido ele ignora e não cria o equipamento + // $isEmpty = false; + // for ($j = 0; $j < 5; $j++) { + // if (empty($dadosLinha[$j])) { + // $isEmpty = true; + // break; + // } + // } + // if ($isEmpty) { + // continue; + // } + + $dadosLinha = $data[$i]; + + // Verifica se a coluna 'fábrica' (primeiro campo) está vazia + if (empty($dadosLinha[0])) { + // Se a coluna 'fábrica' estiver vazia, pule para a próxima linha + continue; + } + + // Verifica se os 5 primeiros campos essenciais estão preenchidos + for ($j = 0; $j < 5; $j++) { + if (empty($dadosLinha[$j])) { + // Se um campo (exceto 'fábrica') estiver vazio, adicione a linha e o índice do campo vazio às linhas ignoradas + $linhasIgnoradas[] = [ + 'linha' => $i, + 'campoVazio' => $nomesColunas[$j] // ou simplesmente $j se não tiver o nome da coluna + ]; + continue 2; // Pula para a próxima linha + } + } + + + // 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 + $juntarArrays = array_combine($nomesColunas, $dadosLinha); + + // vai guardar todos os campos de possiveis novos equipamentos, cada um em um array para multiplos inserts, na base de dados + $datas = array_filter($juntarArrays, 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(); + + if ($existingEquipment) { + + // 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['tag']; + $pendingEquipament->pending_equipment_description = $datas['equipment_Description']; + $pendingEquipament->pending_equipment_serial_number = $datas['n_serie']; + $pendingEquipament->pending_equipment_brand = $datas['modelo']; + $pendingEquipament->pending_company_projects_id = $company_projects_id; + $pendingEquipament->save(); + + // Incremente o contador de PendingEquipments + $countPendingEquipments++; + + // 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['equipment_serial_number']; + $newEquipament->equipment_brand = $datas['equipment_brand']; + $newEquipament->equipment_model = $datas['equipment_model']; + $newEquipament->ispt_number = $isptNumber; + $newEquipament->company_projects_id = $company_projects_id; + + $newEquipament->save(); + + $countNewEquipment++; + + $isptNumber++; + + // 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; + + + $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 = $receveEquipament_type_ID; + $AssociationEquipmentAmbit->ambits_id = $ambit_id; + $AssociationEquipmentAmbit->equipment_id = $receveEquipment_ID; + $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->equipment_id = $receveEquipment_ID; + $JoinsEquipmentsWithTasks->execution_order = $execution_order++; + $JoinsEquipmentsWithTasks->elemental_tasks_id = $TasksAssociationAmbit->elemental_tasks_id; + $JoinsEquipmentsWithTasks->further_tasks_id = null; + // 2 vai significar 'nao' e 1 'sim' + $JoinsEquipmentsWithTasks->inspection = 2; + $JoinsEquipmentsWithTasks->save(); + } + + + $generalAttributes = GeneralAttributesEquipment::all(); + + + foreach ($generalAttributes as $generalAttribute) { + // Verifica se a chave existe em $datas, comparando com os dados da tabela : GeneralAttributesEquipment assim adicionando todos diferentes de NULL relacionados com o equipamento acabado de cria + if (isset($datas[$generalAttribute->general_attributes_equipment_description])) { + + $specificAttribute = new SpecificAttributesEquipmentType; + $specificAttribute->equipment_id = $receveEquipment_ID; + $specificAttribute->equipment_type_id = $receveEquipament_type_ID; + $specificAttribute->general_attributes_equipment_id = $generalAttribute->general_attributes_equipment_id; + // Atribui o valor da chave correspondente em $datas + $specificAttribute->specific_attributes_value = $datas[$generalAttribute->general_attributes_equipment_description]; + + $specificAttribute->save(); + } + } + } + dd($linhasIgnoradas); + + + $pendingEquipments = PendingEquipment::where('pending_company_projects_id', $request->numberProject)->get(); + + // $pendingEquipments = session('pendingEquipments'); + if ($countPendingEquipments != 0) { + // return redirect()->route('test2')->with('Danger', 'Equipamentos Pendentes')->with('listValves', $listValves)->with('pendingEquipments', $pendingEquipments); + return redirect()->route('test2', ['id' => $request->numberProject]) + ->with('danger', 'Equipamentos Pendentes criados : ' . $countPendingEquipments) + ->with('pendingEquipments', $pendingEquipments); + // ->with('success', 'Equipamentos Criados :' . count($listValves)) + } + return redirect()->route('test2', ['id' => $request->numberProject]) + ->with('success', 'Equipamentos Criados :' . $countNewEquipment); + } + + //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('/test3'); + } + + public function showStep3($company_projects_id) + { + $equipments = Equipment::where('company_projects_id', $company_projects_id) + ->get(); + + foreach ($equipments as $equipment) { + $tags = []; + if ($equipment->equipment_type_id == 3) { + $tags = ['@Corpo', '@Flange', '@Obturador']; + } elseif ($equipment->equipment_type_id == 1) { + $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 + ]); + } + } + } + + // 3. Verificar se há algum equipment_id em QrcodesAssociatedEquipment que não existe mais em Equipment e, se sim, excluí-lo. + $allEquipmentIds = Equipment::where('company_projects_id', $company_projects_id)->pluck('equipment_id')->toArray(); + $orphanedEntries = QrcodesAssociatedEquipment::whereNotIn('equipment_id', $allEquipmentIds)->get(); + + foreach ($orphanedEntries as $orphanedEntry) { + $orphanedEntry->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) + { + // dd($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('equipaments') + // ->join('specific_attributes_equipament_types', 'equipaments.equipment_ID', '=', 'specific_attributes_equipament_types.tb_equipament_id') + // ->join('general_attributes_equipaments', 'specific_attributes_equipament_types.specific_Attributes_Equipment_Type_ID', '=', 'general_attributes_equipaments.general_Attributes_Equipment_ID') + // ->select('equipaments.tag', 'general_attributes_equipaments.description', 'specific_attributes_equipament_types.value') + // ->get(); + + $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('test2', ['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); + } + + // public function createEquipamentProject(Request $request) + // { + // $file = $request->file('documento'); + + // // Certifique-se de que um arquivo foi enviado + // if ($file) { + // // Carregue o arquivo Excel + // $spreadsheet = IOFactory::load($file->path()); + + // // Obtenha a primeira planilha + // $worksheet = $spreadsheet->getSheet(0); + + // // Transforme os dados da planilha em um array + // $data = $worksheet->toArray(); + + // $nomesColunas = $data[0]; + + // $dadosLinha6 = $data[6]; + + // $juntarArrays = array_combine($nomesColunas, $dadosLinha6); + + // $datas = array_filter($juntarArrays, function ($chave) { + // return !empty($chave); + // }, ARRAY_FILTER_USE_KEY); + + // $equipamentType = equipament_type::where('equipment_type_name', $datas['tipo_equipamento'])->first(); + // $checkFactory = factorie::where('factories_name', $datas['fabrica'])->first(); + + + // $newEquipament = new equipament; + // //Primeiro tem de derificar se a fabrica existe, senão cria uma. + // $newEquipament->factory_id = $checkFactory->factories_id; + // $newEquipament->equipament_type_id = $equipamentType->equipament_type_id; + // $newEquipament->equipment_Description = $datas['equipment_Description']; + // $newEquipament->tag = $datas['tag']; + // $newEquipament->serial_number = $datas['n_serie']; + // $newEquipament->model = $datas['modelo']; + + // $newEquipament->save(); + + + // $receveEquipment_ID = $newEquipament->id; + // $receveEquipament_type_ID = $newEquipament->equipament_type_id; + + + // // Atributos que você quer buscar e inserir + // $attributes = ["dimension", "dn_ent", "p&id", "n_sap", "isolation", "scaffolding", "grua", "interlocks"]; + + // // $attributes = array_slice($data[0], 7); + + // foreach ($attributes as $attribute) { + + // // Buscar o atributo na tabela general_attributes_equipament + // $generalAttribute = general_attributes_equipament::where('description', $attribute)->first(); + + + // // Se o atributo foi encontrado + // if (!is_null($generalAttribute)) { + // // Criar um novo registro em specific_attributes_equipament_Types + // $specificAttribute = new specific_attributes_equipament_type; + + // $specificAttribute->tb_equipament_id = $receveEquipment_ID; + // $specificAttribute->equipament_Type_id = $receveEquipament_type_ID; + // $specificAttribute->specific_attributes_equipment_type_id = $generalAttribute->general_attributes_equipment_id; + // $specificAttribute->value = $datas[$attribute]; + + // $specificAttribute->save(); + // } + // } + // $listValves = equipament::all(); + + // return redirect()->route('testExcel')->with('success', 'Dados guardados com sucesso')->with('listValves', $listValves); + // } + // } + + + + + // public function createEquipamentProject(Request $request) + // { + // $file = $request->file('documento'); + + // // Certifique-se de que um arquivo foi enviado + // if ($file) { + // // Carregue o arquivo Excel + // $spreadsheet = IOFactory::load($file->path()); + + // // Obtenha a primeira planilha + // $worksheet = $spreadsheet->getSheet(0); + + // // Transforme os dados da planilha em um array + // $data = $worksheet->toArray(); + + // $nomesColunas = $data[0]; + + // // Atributos que você quer buscar e inserir + // $attributes = ["dimension", "dn_ent", "p&id", "n_sap", "isolation", "scaffolding", "grua", "interlocks"]; + + // // Comece a partir da sexta linha + // for ($i = 6; $i < count($data); $i++) { + + // $dadosLinha = $data[$i]; + + // //Se não preencher o campo $dadosLinha[0], não cria um novo equipamento + // //Trocar pelos 5 primeiros + // if (empty($dadosLinha[0])) { + // continue; + // } + + + // $juntarArrays = array_combine($nomesColunas, $dadosLinha); + + // $datas = array_filter($juntarArrays, function ($chave) { + // return !empty($chave); + // }, ARRAY_FILTER_USE_KEY); + + // $equipmentType = EquipmentType::where('equipment_type_name', $datas['tipo_equipamento'])->first(); + + // $checkFactory = Unit::where('unit_name', $datas['fabrica'])->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['tag']) + // ->first(); + + // if ($existingEquipment) { + // // 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['tag']; + // $pendingEquipament->pending_equipment_description = $datas['equipment_Description']; + // $pendingEquipament->pending_equipment_serial_number = $datas['n_serie']; + // $pendingEquipament->pending_equipment_brand = $datas['modelo']; + + // $pendingEquipament->save(); + + // // Adicione uma variável de sessão para indicar que um equipamento pendente foi criado. + // session(['pendingEquipmentCreated' => true]); + + // // Adicione uma variável de sessão para indicar que um equipamento pendente foi criado. + // session()->push('pendingEquipments', $pendingEquipament); + + // // 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['tag']; + // $newEquipament->equipment_serial_number = $datas['n_serie']; + // $newEquipament->equipment_model = $datas['modelo']; + + // $newEquipament->save(); + + // $receveEquipment_ID = $newEquipament->equipment_id; + + // $receveEquipament_type_ID = $newEquipament->equipment_type_id; + + + // foreach ($attributes as $attribute) { + + // $generalAttribute = GeneralAttributesEquipment::where('general_attributes_equipment_description', $attribute)->first(); + + // if (!is_null($generalAttribute)) { + + // $specificAttribute = new SpecificAttributesEquipmentType; + + // $specificAttribute->equipment_id = $receveEquipment_ID; + // $specificAttribute->equipment_type_id = $receveEquipament_type_ID; + // $specificAttribute->specific_attributes_equipment_type_id = $generalAttribute->general_attributes_equipment_id; + // $specificAttribute->specific_attributes_value = $datas[$attribute]; + + // // $specificAttribute->save(); + // } + // } + // } + + // $listValves = Equipment::all(); + // $pendingEquipments = PendingEquipment::all(); + + // // return redirect()->route('createProject')->with('success', 'Dados guardados com sucesso')->with('listValves', $listValves); + + // // return redirect()->route('createProject')->with('success', 'Dados guardados com sucesso')->with('listValves', $listValves)->with('pendingEquipments', $pendingEquipments); + + // $listValves = Equipment::all(); + // $pendingEquipments = session('pendingEquipments'); + // if ($pendingEquipments) { + // return redirect()->route('createProject')->with('success', 'Dados guardados com sucesso')->with('listValves', $listValves)->with('pendingEquipments', $pendingEquipments); + // } else { + // return redirect()->route('createProject')->with('success', 'Dados guardados com sucesso')->with('listValves', $listValves); + // } + // } + // } +} diff --git a/app/Http/Controllers/CreateProjectController.php b/app/Http/Controllers/CreateProjectController.php index 85c49cb3..9dfd9d8b 100755 --- a/app/Http/Controllers/CreateProjectController.php +++ b/app/Http/Controllers/CreateProjectController.php @@ -2,6 +2,7 @@ namespace App\Http\Controllers; +use App\Models\EquipmentWorkHistory; use Illuminate\Http\Request; use Illuminate\Support\Facades\DB; use PhpOffice\PhpSpreadsheet\IOFactory; @@ -36,6 +37,106 @@ class CreateProjectController extends Controller { + 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', 'Ambito selecionado, igual ao anterior!'); + // } else { + // $receiveDataEquipmentAssociationAmbit->ambits_id = $receiveAmbitEquipmentId; + // $receiveDataEquipmentAssociationAmbit->save(); + + + // } + + $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) + { + $receiveEquipmentId = $request->equipmentId; + $receiveEquipment = Equipment::where('equipment_id', $receiveEquipmentId)->first(); + $receiveStatus = $request->deleteEquipmentProject; + + if ($receiveStatus == 'complete') { + EquipmentWorkHistory::where('equipment_id', $receiveEquipment->equipment_id) + ->where('company_projects_id', $receiveEquipment->company_projects_id) + ->delete(); + $receiveEquipment->delete(); + + return redirect()->back() + ->with('success', 'Equipamento: ' . $receiveEquipment->equipment_id . ' excluído com sucesso!'); + } else { + $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) { @@ -174,7 +275,7 @@ public function receiveUnitsForExcelTemplate($numberProject) $receveCompanyProject = CompanyProject::where('company_projects_id', $numberProject)->first(); $recevePlant = Plant::where('plant_id', $receveCompanyProject->plant_id)->first(); $receveUnits = Unit::where('plant_id', $recevePlant->plant_id)->get(); - $filePath = public_path('templateExcel/TestTemplate.xlsx'); + $filePath = public_path('templateExcel/Valves_Template.xlsx'); // Load the spreadsheet $spreadsheet = IOFactory::load($filePath); // Get the second sheet @@ -185,8 +286,13 @@ public function receiveUnitsForExcelTemplate($numberProject) $sheet->setCellValue('D' . $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, 'Valves_Template.xlsx'); + return $this->createDownloadResponse($spreadsheet, $fileName); } protected function createDownloadResponse($spreadsheet, $filename) @@ -659,6 +765,7 @@ public function processStep1(Request $request) public function showStep2($company_projects_id) { + $groupedArrayForPendingEquipments = session('groupedArrayForPendingEquipments'); // Verifique se a etapa 1 foi concluída // if (!session('form_data.step1')) { @@ -693,10 +800,11 @@ public function showStep2($company_projects_id) // $listEquipmentsProjects = Equipment::with(['unit', 'equipmentType', 'equipmentAssociationAmbit.ambitsEquipment']) // ->where('company_projects_id', $company_projects_id) // ->get(); + $listEquipmentsProjects = Equipment::with([ 'unit', 'equipmentType', - 'equipmentAssociationAmbit.ambitsEquipment', + // 'equipmentAssociationAmbit.ambitsEquipment', 'specificAttributes' => function ($query) { $query->orderBy('specific_attributes_value', 'asc'); } @@ -704,7 +812,6 @@ public function showStep2($company_projects_id) ->where('company_projects_id', $company_projects_id) ->get(); - // dd($checkUnits); $pendingEquipments = PendingEquipment::where('pending_company_projects_id', $numberProject)->get(); if (!$pendingEquipments->isEmpty()) { @@ -716,13 +823,15 @@ public function showStep2($company_projects_id) ->with('typeEquipments', $typeEquipments) ->with('checkEquipments', $checkEquipments) ->with('checkUnits', $checkUnits) - ->with('receiveNumberProject', $project); + ->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); } @@ -770,6 +879,7 @@ public function createEquipmentManual(Request $request) $newEquipmentProject->unit_id = $newUnit->unit_id; } + $newEquipmentProject->equipment_type_id = $request->equipmentTypeId; $newEquipmentProject->equipment_tag = $request->tag; $newEquipmentProject->equipment_description = $request->equipmentDescription; @@ -780,12 +890,21 @@ public function createEquipmentManual(Request $request) $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; + $newEquipmentWorkHistorys->equipment_id = $equipmentID; + $newEquipmentWorkHistorys->ispt_number = 0; + $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())) @@ -805,20 +924,22 @@ public function createEquipmentManual(Request $request) } // 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->equipment_id = $equipmentID; - $AssociationEquipmentAmbit->save(); + $AssociationEquipmentAmbit->equipmentWorkHistorys_id = $equipmentWorkHistorysID; + $AssociationEquipmentAmbit->save(); $execution_order = 1; @@ -827,7 +948,7 @@ public function createEquipmentManual(Request $request) foreach ($TasksAssociationAmbits as $TasksAssociationAmbit) { $JoinsEquipmentsWithTasks = new OrderEquipmentTasks; - $JoinsEquipmentsWithTasks->equipment_id = $equipmentID; + $JoinsEquipmentsWithTasks->equipmentWorkHistorys_id = $equipmentWorkHistorysID; $JoinsEquipmentsWithTasks->execution_order = $execution_order++; $JoinsEquipmentsWithTasks->elemental_tasks_id = $TasksAssociationAmbit->elemental_tasks_id; $JoinsEquipmentsWithTasks->further_tasks_id = null; @@ -835,7 +956,6 @@ public function createEquipmentManual(Request $request) $JoinsEquipmentsWithTasks->save(); } - // O $request->numberProject e sempre necessario retornar para indicar a obra que se esta modificando... return redirect()->route('test2', ['id' => $request->numberProject]) ->with('success', 'Equipamento criado com sucesso') @@ -849,58 +969,70 @@ public function receiveIdEquipment(Equipment $equipment) public function processStep2(Request $request) { - // dd($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; // 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 a tabela : general_attributes_equipaments + // 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 - $nomesColunas = $data[0]; - - // dd($nomesColunas); - + $columnNames = $data[0]; $countPendingEquipments = 0; $countNewEquipment = 0; - // Comece a partir da sexta linha + // 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++) { - $dadosLinha = $data[$i]; + $dataLines = $data[$i]; - // Verifica se os 5 primeiros campos essenciais estao preenchidos, um deles não estiver preenchido ele ignora e não cria o equipamento - $isEmpty = false; - for ($j = 0; $j < 5; $j++) { - if (empty($dadosLinha[$j])) { - $isEmpty = true; - break; - } - } - if ($isEmpty) { + // 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 + } + } + + 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 + } + // 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 - $juntarArrays = array_combine($nomesColunas, $dadosLinha); + $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($juntarArrays, function ($chave) { + $datas = array_filter($joinArrays, function ($chave) { return !empty($chave); }, ARRAY_FILTER_USE_KEY); @@ -917,22 +1049,46 @@ public function processStep2(Request $request) 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['tag']; - $pendingEquipament->pending_equipment_description = $datas['equipment_Description']; - $pendingEquipament->pending_equipment_serial_number = $datas['n_serie']; - $pendingEquipament->pending_equipment_brand = $datas['modelo']; + $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; } @@ -943,22 +1099,31 @@ public function processStep2(Request $request) $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['equipment_serial_number']; - $newEquipament->equipment_brand = $datas['equipment_brand']; - $newEquipament->equipment_model = $datas['equipment_model']; - $newEquipament->ispt_number = $isptNumber; + $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(); $countNewEquipment++; - $isptNumber++; - // 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; + $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(); @@ -968,9 +1133,10 @@ public function processStep2(Request $request) //Criar associacao do equipamento ao Âmbito $AssociationEquipmentAmbit = new EquipmentAssociationAmbit; + $AssociationEquipmentAmbit->equipment_type_id = $receveEquipament_type_ID; $AssociationEquipmentAmbit->ambits_id = $ambit_id; - $AssociationEquipmentAmbit->equipment_id = $receveEquipment_ID; + $AssociationEquipmentAmbit->equipmentWorkHistorys_id = $recebeNewEquipmentWorkHistoryID; $AssociationEquipmentAmbit->save(); $execution_order = 1; @@ -980,7 +1146,8 @@ public function processStep2(Request $request) foreach ($TasksAssociationAmbits as $TasksAssociationAmbit) { $JoinsEquipmentsWithTasks = new OrderEquipmentTasks; - $JoinsEquipmentsWithTasks->equipment_id = $receveEquipment_ID; + + $JoinsEquipmentsWithTasks->equipmentWorkHistorys_id = $recebeNewEquipmentWorkHistoryID; $JoinsEquipmentsWithTasks->execution_order = $execution_order++; $JoinsEquipmentsWithTasks->elemental_tasks_id = $TasksAssociationAmbit->elemental_tasks_id; $JoinsEquipmentsWithTasks->further_tasks_id = null; @@ -992,7 +1159,6 @@ public function processStep2(Request $request) $generalAttributes = GeneralAttributesEquipment::all(); - foreach ($generalAttributes as $generalAttribute) { // Verifica se a chave existe em $datas, comparando com os dados da tabela : GeneralAttributesEquipment assim adicionando todos diferentes de NULL relacionados com o equipamento acabado de cria if (isset($datas[$generalAttribute->general_attributes_equipment_description])) { @@ -1009,18 +1175,43 @@ public function processStep2(Request $request) } } + // 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(); - // $pendingEquipments = session('pendingEquipments'); - if ($countPendingEquipments != 0) { - // return redirect()->route('test2')->with('Danger', 'Equipamentos Pendentes')->with('listValves', $listValves)->with('pendingEquipments', $pendingEquipments); + // Verifica se foram criados equipamentos pendentes,e se nesses pendentes vieram do execel ou da base de dados, alem de indicar as linha nao preenchidas. + // if ($countPendingEquipments != 0 && !empty($pendenteLogs) && !empty($linhasIgnoradas)) { + // return redirect()->route('test2', ['id' => $request->numberProject]) + // ->with('danger', 'Equipamentos Pendentes criados : ' . $countPendingEquipments) + // ->with('dangerPendenteLogs', ['linhasIgnoradas' => $linhasIgnoradas, 'pendenteLogs' => $pendenteLogs]) + // ->with('pendingEquipments', $pendingEquipments); + // } + // return redirect()->route('test2', ['id' => $request->numberProject]) + // ->with('success', 'Equipamentos Criados :' . $countNewEquipment); + + 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('test2', ['id' => $request->numberProject]) - ->with('danger', 'Equipamentos Pendentes criados : ' . $countPendingEquipments) + ->with('danger', 'Equipamentos Pendentes criados: ' . $countPendingEquipments) + ->with('dangerLogs', $ignoredLines) + ->with('equipmentPendingLogs', $equipmentPendingLogs) ->with('pendingEquipments', $pendingEquipments); - // ->with('success', 'Equipamentos Criados :' . count($listValves)) + } 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('test2', ['id' => $request->numberProject]) + ->with('success', 'Equipamentos Criados: ' . $countNewEquipment) + ->with('dangerLogs', $ignoredLines); } - return redirect()->route('test2', ['id' => $request->numberProject]) - ->with('success', 'Equipamentos Criados :' . $countNewEquipment); + } //Nao chega aqui ainda pois volta para a pagina com dados ja carregados. @@ -1156,11 +1347,7 @@ public function processStep3(Request $request) public function index() { - // $results = DB::table('equipaments') - // ->join('specific_attributes_equipament_types', 'equipaments.equipment_ID', '=', 'specific_attributes_equipament_types.tb_equipament_id') - // ->join('general_attributes_equipaments', 'specific_attributes_equipament_types.specific_Attributes_Equipment_Type_ID', '=', 'general_attributes_equipaments.general_Attributes_Equipment_ID') - // ->select('equipaments.tag', 'general_attributes_equipaments.description', 'specific_attributes_equipament_types.value') - // ->get(); + $results = DB::table('equipments') ->join('specific_attributes_equipament_types', 'equipments.equipment_id', '=', 'specific_attributes_equipament_types.equipment_id') @@ -1284,205 +1471,4 @@ public function getAttributes($id) $equipment = Equipment::with('specificAttributes')->find($id); return response()->json($equipment->specificAttributes); } - - // public function createEquipamentProject(Request $request) - // { - // $file = $request->file('documento'); - - // // Certifique-se de que um arquivo foi enviado - // if ($file) { - // // Carregue o arquivo Excel - // $spreadsheet = IOFactory::load($file->path()); - - // // Obtenha a primeira planilha - // $worksheet = $spreadsheet->getSheet(0); - - // // Transforme os dados da planilha em um array - // $data = $worksheet->toArray(); - - // $nomesColunas = $data[0]; - - // $dadosLinha6 = $data[6]; - - // $juntarArrays = array_combine($nomesColunas, $dadosLinha6); - - // $datas = array_filter($juntarArrays, function ($chave) { - // return !empty($chave); - // }, ARRAY_FILTER_USE_KEY); - - // $equipamentType = equipament_type::where('equipment_type_name', $datas['tipo_equipamento'])->first(); - // $checkFactory = factorie::where('factories_name', $datas['fabrica'])->first(); - - - // $newEquipament = new equipament; - // //Primeiro tem de derificar se a fabrica existe, senão cria uma. - // $newEquipament->factory_id = $checkFactory->factories_id; - // $newEquipament->equipament_type_id = $equipamentType->equipament_type_id; - // $newEquipament->equipment_Description = $datas['equipment_Description']; - // $newEquipament->tag = $datas['tag']; - // $newEquipament->serial_number = $datas['n_serie']; - // $newEquipament->model = $datas['modelo']; - - // $newEquipament->save(); - - - // $receveEquipment_ID = $newEquipament->id; - // $receveEquipament_type_ID = $newEquipament->equipament_type_id; - - - // // Atributos que você quer buscar e inserir - // $attributes = ["dimension", "dn_ent", "p&id", "n_sap", "isolation", "scaffolding", "grua", "interlocks"]; - - // // $attributes = array_slice($data[0], 7); - - // foreach ($attributes as $attribute) { - - // // Buscar o atributo na tabela general_attributes_equipament - // $generalAttribute = general_attributes_equipament::where('description', $attribute)->first(); - - - // // Se o atributo foi encontrado - // if (!is_null($generalAttribute)) { - // // Criar um novo registro em specific_attributes_equipament_Types - // $specificAttribute = new specific_attributes_equipament_type; - - // $specificAttribute->tb_equipament_id = $receveEquipment_ID; - // $specificAttribute->equipament_Type_id = $receveEquipament_type_ID; - // $specificAttribute->specific_attributes_equipment_type_id = $generalAttribute->general_attributes_equipment_id; - // $specificAttribute->value = $datas[$attribute]; - - // $specificAttribute->save(); - // } - // } - // $listValves = equipament::all(); - - // return redirect()->route('testExcel')->with('success', 'Dados guardados com sucesso')->with('listValves', $listValves); - // } - // } - - - - - // public function createEquipamentProject(Request $request) - // { - // $file = $request->file('documento'); - - // // Certifique-se de que um arquivo foi enviado - // if ($file) { - // // Carregue o arquivo Excel - // $spreadsheet = IOFactory::load($file->path()); - - // // Obtenha a primeira planilha - // $worksheet = $spreadsheet->getSheet(0); - - // // Transforme os dados da planilha em um array - // $data = $worksheet->toArray(); - - // $nomesColunas = $data[0]; - - // // Atributos que você quer buscar e inserir - // $attributes = ["dimension", "dn_ent", "p&id", "n_sap", "isolation", "scaffolding", "grua", "interlocks"]; - - // // Comece a partir da sexta linha - // for ($i = 6; $i < count($data); $i++) { - - // $dadosLinha = $data[$i]; - - // //Se não preencher o campo $dadosLinha[0], não cria um novo equipamento - // //Trocar pelos 5 primeiros - // if (empty($dadosLinha[0])) { - // continue; - // } - - - // $juntarArrays = array_combine($nomesColunas, $dadosLinha); - - // $datas = array_filter($juntarArrays, function ($chave) { - // return !empty($chave); - // }, ARRAY_FILTER_USE_KEY); - - // $equipmentType = EquipmentType::where('equipment_type_name', $datas['tipo_equipamento'])->first(); - - // $checkFactory = Unit::where('unit_name', $datas['fabrica'])->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['tag']) - // ->first(); - - // if ($existingEquipment) { - // // 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['tag']; - // $pendingEquipament->pending_equipment_description = $datas['equipment_Description']; - // $pendingEquipament->pending_equipment_serial_number = $datas['n_serie']; - // $pendingEquipament->pending_equipment_brand = $datas['modelo']; - - // $pendingEquipament->save(); - - // // Adicione uma variável de sessão para indicar que um equipamento pendente foi criado. - // session(['pendingEquipmentCreated' => true]); - - // // Adicione uma variável de sessão para indicar que um equipamento pendente foi criado. - // session()->push('pendingEquipments', $pendingEquipament); - - // // 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['tag']; - // $newEquipament->equipment_serial_number = $datas['n_serie']; - // $newEquipament->equipment_model = $datas['modelo']; - - // $newEquipament->save(); - - // $receveEquipment_ID = $newEquipament->equipment_id; - - // $receveEquipament_type_ID = $newEquipament->equipment_type_id; - - - // foreach ($attributes as $attribute) { - - // $generalAttribute = GeneralAttributesEquipment::where('general_attributes_equipment_description', $attribute)->first(); - - // if (!is_null($generalAttribute)) { - - // $specificAttribute = new SpecificAttributesEquipmentType; - - // $specificAttribute->equipment_id = $receveEquipment_ID; - // $specificAttribute->equipment_type_id = $receveEquipament_type_ID; - // $specificAttribute->specific_attributes_equipment_type_id = $generalAttribute->general_attributes_equipment_id; - // $specificAttribute->specific_attributes_value = $datas[$attribute]; - - // // $specificAttribute->save(); - // } - // } - // } - - // $listValves = Equipment::all(); - // $pendingEquipments = PendingEquipment::all(); - - // // return redirect()->route('createProject')->with('success', 'Dados guardados com sucesso')->with('listValves', $listValves); - - // // return redirect()->route('createProject')->with('success', 'Dados guardados com sucesso')->with('listValves', $listValves)->with('pendingEquipments', $pendingEquipments); - - // $listValves = Equipment::all(); - // $pendingEquipments = session('pendingEquipments'); - // if ($pendingEquipments) { - // return redirect()->route('createProject')->with('success', 'Dados guardados com sucesso')->with('listValves', $listValves)->with('pendingEquipments', $pendingEquipments); - // } else { - // return redirect()->route('createProject')->with('success', 'Dados guardados com sucesso')->with('listValves', $listValves); - // } - // } - // } } diff --git a/app/Http/Controllers/ExecutionProjectController.php b/app/Http/Controllers/ExecutionProjectController.php index 92a55e39..6d5097b8 100755 --- a/app/Http/Controllers/ExecutionProjectController.php +++ b/app/Http/Controllers/ExecutionProjectController.php @@ -80,7 +80,6 @@ public function getDataEquipment(Request $request) $receiveAllClients = $request->get('receiveAllClients'); $receiveAllPlants = $request->get('receiveAllPlants'); - $receiveAllUnits = $request->get('receiveAllUnits'); $receiveEquipmentsType = $request->get('receiveEquipmentsType'); @@ -107,14 +106,12 @@ public function getDataEquipment(Request $request) $query = Equipment::with('equipmentType', 'unit') ->whereIn('unit_id', $unitsIds) - ->select(['equipment_id', 'ispt_number', 'equipment_tag', 'unit_id', 'equipment_type_id']); - - + ->select(['equipment_id', 'equipment_tag', 'unit_id', 'equipment_type_id']); } else { // Query padrão que todas as dataTables recebem, a partir dele fazemos os filt $query = Equipment::with('equipmentType', 'unit') - ->select(['equipment_id', 'ispt_number', 'equipment_tag', 'unit_id', 'equipment_type_id']); + ->select(['equipment_id', 'equipment_tag', 'unit_id', 'equipment_type_id']); } // Consultas para a Criacao da Obra, Ambas vao ser diferentes, pois na creacao, recebes os equipamentos por obra, porem no portifolio vamos buscar todos. @@ -171,17 +168,41 @@ public function getDataEquipment(Request $request) }) ->addColumn('action', function ($equipment) use ($numberProject) { - // Verifica se $numberProject não é nulo - if (!is_null($numberProject)) { - // Se não for nulo, usa a rota 'test11' - $actionBtn = ''; - } else { - // Se for nulo, usa a rota 'test22' - $actionBtn = ''; - } - return $actionBtn; + $dropdownHtml = '