diff --git a/app/Console/Kernel.php b/app/Console/Kernel.php index 2e37f3ae..75ff65db 100755 --- a/app/Console/Kernel.php +++ b/app/Console/Kernel.php @@ -36,7 +36,6 @@ protected function schedule(Schedule $schedule): void 'entry_date' => null, ]); - // Adicione outras tarefas necessárias aqui })->everyMinute(); } diff --git a/app/Http/Controllers/CreateProjectController.php b/app/Http/Controllers/CreateProjectController.php index 23344515..45274150 100755 --- a/app/Http/Controllers/CreateProjectController.php +++ b/app/Http/Controllers/CreateProjectController.php @@ -1,5 +1,6 @@ equipment_brand = $datas['brand']; $newEquipament->equipment_model = $datas['model']; $newEquipament->company_projects_id = $company_projects_id; + $newEquipament->save(); + $countEquipment++; - //Deve adicionar tambem os outros atributos espesificos para o equipameto. + //Criar 'specific_attributes_equipament_types' de acordo com o escrito, na linha do excel + $generalAttributes = GeneralAttributesEquipment::all(); + + foreach ($generalAttributes as $generalAttribute) { + // Verifica se a chave existe em $datas + if (isset($datas[$generalAttribute->general_attributes_equipment_description])) { + $specificAttribute = new SpecificAttributesEquipmentType; + $specificAttribute->equipment_id = $newEquipament->equipment_id; + $specificAttribute->equipment_type_id = $newEquipament->equipment_type_id; + $specificAttribute->general_attributes_equipment_id = $generalAttribute->general_attributes_equipment_id; + $specificAttribute->specific_attributes_value = $datas[$generalAttribute->general_attributes_equipment_description]; + + $specificAttribute->save(); + } + } //Criar o equipment Work History $newEquipmentWorkHistory = new EquipmentWorkHistory; @@ -1482,7 +1503,6 @@ function normalize($value) $newEquipmentWorkHistory->company_projects_id = $company_projects_id; $newEquipmentWorkHistory->equipment_status_project = 0; - //Se o projecto atual for uma adicao de equipamentos extras, vai ter o order_project como 5, sendo assim todos os equipamentos adicionados vai ser equipamentos extras if ($detailsCompanyProject->order_project == 5) { $newEquipmentWorkHistory->extra_equipment = 1; } else { @@ -1514,15 +1534,14 @@ function normalize($value) $JoinsEquipmentsWithTasks->execution_order = $execution_order++; $JoinsEquipmentsWithTasks->equipmentWorkHistorys_id = $newEquipmentWorkHistory->equipmentWorkHistorys_id; $JoinsEquipmentsWithTasks->elemental_tasks_id = $TasksAssociationAmbit->elemental_tasks_id; + $JoinsEquipmentsWithTasks->save(); } // Cria um array agrupado $groupedArrayForPendingEquipments = [$documentType, [$timestamp, $equipmentPendingLogs]]; // Armazenar $groupedArrayForPendingEquipments na sessão - //------- Porem agora nao deve ser guardado em uma sessao em sim em uma tabela da Db ate terminar(concluir) a Obra session(['groupedArrayForPendingEquipments' => $groupedArrayForPendingEquipments]); - // $pendingEquipments = PendingEquipment::where('pending_company_projects_id', $request->numberProject)->get(); $equipmentPendingLogs[] = [ 'typePendingLog' => 3, @@ -1531,7 +1550,6 @@ function normalize($value) ]; continue; } - // Se a linha não for duplicada nem no Excel nem na base de dados, // a linha é considerada para a criação de um novo equipamento. // Sua lógica para criar um novo equipamento pode ser inserida aqui. @@ -1557,7 +1575,7 @@ function normalize($value) return redirect()->route('articulated_2', ['projectID' => $request->numberProject]) ->with('success', 'Equipamentos criados com sucesso !'); - //Se nao existir arquivo ou nao for compativel + //Se nao existir arquivo ou nao for compativel } elseif ($detailsCompanyProject->order_project == 5) { return redirect()->route('changeFromExecutionToPlanning', ['projectID' => $request->numberProject]) ->with('danger', 'Arquivo ignorado , por nao ser compativel com a template 4.0'); diff --git a/app/Http/Controllers/ExecutionProjectController.php b/app/Http/Controllers/ExecutionProjectController.php index d50b5e42..8b9a10c0 100755 --- a/app/Http/Controllers/ExecutionProjectController.php +++ b/app/Http/Controllers/ExecutionProjectController.php @@ -779,19 +779,18 @@ public function receiveDetailsEquipmentsProject(Request $request) //Para a tabela com status = pending' deve ir equipamentos com status = 1 pois estao pendentes para Aprovar // Para os restantes equipamentos vao para a tabela que lista os equipamentos da Obra,porem apenas os equipmentos com status = 0 //Equipamentos concluidos e aprovados,vao ter o status = 2 e servir apenas para visualizar - - // $status = $tableType === 'pending' ? 1 : 0; - // $query->where('equipment_status_project', $status); - + // Definir o status com base no tipo de tabela if ($tableType === 'pending') { - $status = 1; // Equipamentos pendentes para aprovação + $statuses = [1, 4]; // Equipamentos pendentes para aprovação + $query->whereIn('equipment_status_project', $statuses); } else if ($tableType === 'completed') { $status = 2; // Equipamentos concluídos e aprovados + $query->where('equipment_status_project', $status); } else { $status = 0; // Outros equipamentos em andamento (normal) + $query->where('equipment_status_project', $status); } - $query->where('equipment_status_project', $status); }); $query = $initialQuery->get(); // Obtém a coleção de equipamentos com base nos critérios @@ -828,51 +827,4 @@ public function receiveDetailsEquipmentsProject(Request $request) } - - - // public function receiveEquipmentsExecutionProject($receiveNumberProject) - // { - // // Recebe os dados vindos da funcao 'data' criada na view - // $equipment_type_id = request('equipment_type_id'); - // $ambits_id = request('ambits_id'); - - // //Recebe sempre apenas os equipamentos relacionados a obra - // $model = Equipment::where('company_projects_id', $receiveNumberProject); - - // // Caso 'equipment_type_id' seja '#', mostra todos os equipamentos - // if ($equipment_type_id == '#') { - // $model = Equipment::query()->with(['equipmentType', 'unit', 'equipmentAssociationAmbit.ambitsEquipment']); - // } - // // Caso 'equipment_type_id' não seja '#', filtra os equipamentos por tipo e Âmbito (caso 'ambits_id' não seja '#') - // else { - // $equipment_type_id = intval($equipment_type_id); - // $model = Equipment::where('equipments.equipment_type_id', $equipment_type_id) - // ->join('equipment_association_ambits', 'equipments.equipment_id', '=', 'equipment_association_ambits.equipment_id') - // ->with(['equipmentType', 'unit', 'equipmentAssociationAmbit.ambitsEquipment']); - - // if ($ambits_id != '#') { - // $ambits_id = intval($ambits_id); - // $model->where('equipment_association_ambits.ambits_id', $ambits_id); - // } - // } - - // return DataTables::of($model) - // ->addColumn('equipment_type', function ($row) { - // return $row->equipmentType->equipment_type_name; - // }) - // ->addColumn('Ambits', function ($row) { - // return $row->equipmentAssociationAmbit->ambitsEquipment->ambits_description; - // }) - // ->addColumn('order_tasks', function ($row) { - // return $row->orderEquipmentTasks->map(function ($task) { - // return $task->elementalTask->elemental_tasks_code; - // })->implode('-'); - // }) - // ->addColumn('current_task', function ($row) { - // return $row->controlEquipmentWorkstation->map(function ($task) { - // return $task->elementalTask->elemental_tasks_code; - // })->implode('-'); - // }) - // ->toJson(); - // } -} +} \ No newline at end of file diff --git a/app/Http/Controllers/ProjectoDatacontroller.php b/app/Http/Controllers/ProjectoDatacontroller.php index 0334117d..fee3d982 100755 --- a/app/Http/Controllers/ProjectoDatacontroller.php +++ b/app/Http/Controllers/ProjectoDatacontroller.php @@ -148,14 +148,15 @@ public function checkProjectIsptNumber(Request $request, $projectId = null) public function showAmbitDetailsProjectHistory($equipmentStatus, $projectID, $equipmentID) { + $detailsProject = CompanyProject::where('company_projects_id', $projectID)->first(); $detailsCliente = Plant::where('plant_id', $detailsProject->plant_id)->first(); $detailsProject->user_id = $detailsCliente->user_id; - $detailsEquipmentWorkProject = EquipmentWorkHistory::where('equipment_id', $equipmentID) ->where('company_projects_id', $projectID)->first(); + //Recebe os comentarios do equipamento $receiveComments = EquipmentComment::with(['user']) ->where('equipmentWorkHistorys_id', $detailsEquipmentWorkProject->equipmentWorkHistorys_id) ->where('company_projects_id', $detailsProject->company_projects_id) @@ -172,26 +173,19 @@ public function showAmbitDetailsProjectHistory($equipmentStatus, $projectID, $eq // OBS : Porem deveria confirma se a tarefa foi mesmo concluida. // $receiveAllTasksHistiory = ControlEquipmentWorkstation::where('equipmentWorkHistorys_id', $detailsEquipmentWorkProject->equipmentWorkHistorys_id)->get(); - $receiveAllTasksEquipmentInHistory = OrderEquipmentTasks::where('equipmentWorkHistorys_id', $detailsEquipmentWorkProject->equipmentWorkHistorys_id)->get(); - - $receiveAmbit = EquipmentAssociationAmbit::where('equipmentWorkHistorys_id', $detailsEquipmentWorkProject->equipmentWorkHistorys_id)->first(); // $tasksAssociatedWithAmbit = TasksAssociationAmbits::where('ambits_equipment_id', $receiveAmbit->ambits_id)->get(); - $tasksAssociatedWithAmbit = TasksAssociationAmbits::with('elementalTask') - ->where('ambits_equipment_id', $receiveAmbit->ambits_id) + // Busca todas as tarefas do equipamento na ordem de execução + $receiveAllTasksEquipmentInHistory = OrderEquipmentTasks::where('equipmentWorkHistorys_id', $detailsEquipmentWorkProject->equipmentWorkHistorys_id) + ->orderBy('execution_order', 'asc') ->get(); - foreach ($tasksAssociatedWithAmbit as $taskAssociation) { - if ($taskAssociation->elementalTask) { - // Adiciona diretamente ao objeto TasksAssociationAmbits - $taskAssociation->elemental_task_description = $taskAssociation->elementalTask->elemental_tasks_description; - } else { - // Defina como null ou algum valor padrão se não houver tarefa elementar associada - $taskAssociation->elemental_task_description = null; - } - } - $receiveAllTasksHistiory = ControlEquipmentWorkstation::with('workstationsTaskAnswers') + // Em seguida, obtenha todos os IDs de tarefas elementares de $receiveAllTasksEquipmentInHistory + $equipmentTasksIds = $receiveAllTasksEquipmentInHistory->pluck('elemental_tasks_id')->filter()->unique(); + + // Recebe apenas as tarefas já feitas + $completedTasksHistory = ControlEquipmentWorkstation::with('workstationsTaskAnswers') ->where('equipmentWorkHistorys_id', $detailsEquipmentWorkProject->equipmentWorkHistorys_id) ->whereNotNull('entry_date') // Verifica se 'entry_date' não é null ->whereNotNull('departure_date') // Verifica se 'departure_date' não é null @@ -199,7 +193,11 @@ public function showAmbitDetailsProjectHistory($equipmentStatus, $projectID, $eq ->orderBy('elemental_tasks_id', 'asc') ->get(); - foreach ($receiveAllTasksHistiory as $taskHistory) { + // Cria uma coleção para armazenar todas as tarefas, concluídas e não concluídas + $receiveAllTasksHistiory = collect(); + + // Adiciona as tarefas concluídas à coleção principal + foreach ($completedTasksHistory as $taskHistory) { $taskHistory->cardTypeStyle = 'gray'; // Adiciona o campo 'cardTypeStyle' // Obtém o primeiro registro de workstationsTaskAnswers ou define como null se não existir @@ -251,18 +249,60 @@ public function showAmbitDetailsProjectHistory($equipmentStatus, $projectID, $eq } else { $taskHistory->runtime = 'N/A'; // Ou qualquer valor padrão que você prefira } + + // Adiciona o taskHistory à coleção principal + $receiveAllTasksHistiory->push($taskHistory); } - // Nao esta a receber itens + // Agrupar tarefas por elemental_tasks_id e ordenar por departure_date + $tasksGrouped = $completedTasksHistory->groupBy('elemental_tasks_id')->map(function ($group) { + return $group->sortByDesc('departure_date'); + }); - // dd($allWorkstationsTaskAnswers); - // Agora cada objeto dentro de $tasksAssociatedWithAmbit tem uma propriedade 'elemental_task_description'. + // Processar tarefas concluídas + foreach ($tasksGrouped as $elemental_tasks_id => $tasks) { + // A tarefa mais recente + $latestTask = $tasks->first(); + // Os históricos (excluindo a mais recente) + $historyTasks = $tasks->slice(1); - //buscar Tarfas e tempo de execussao pelo control, assim como suas respostas. - // dd($receiveAmbit); + $receiveAllTasksHistiory->push((object) [ + 'latest' => $latestTask, + 'history' => $historyTasks, + ]); + } + + // Adiciona as tarefas não concluídas à coleção principal + $incompleteTasks = $equipmentTasksIds->diff($completedTasksHistory->pluck('elemental_tasks_id')); - return view('projectsClients.showAmbitDetailProjectHistory', compact('receiveComments', 'equipmentStatus', 'detailsProject', 'receiveAmbit', 'receiveAllTasksHistiory', 'detalsEquipment','detailsEquipmentWorkProject')); + foreach ($incompleteTasks as $taskId) { + // Busca os dados da tarefa elementar + $elementalTask = ElementalTasks::where('elemental_tasks_id', $taskId)->first(); + + $receiveAllTasksHistiory->push((object) [ + 'latest' => (object) [ + 'elemental_tasks_id' => $taskId, + 'control_equipment_workstation_id' => 'N/A', + 'cardType' => 'blue', + 'cardTypeStyle' => 'blue', + 'formatted_answers' => [], + 'entry_date' => 'N/A', + 'runtime' => 'N/A', + 'elementalTask' => (object) [ + 'elemental_tasks_code' => $elementalTask ? $elementalTask->elemental_tasks_code : null, + 'elemental_tasks_description' => $elementalTask ? $elementalTask->elemental_tasks_description : null + ] + ], + 'history' => collect(), // Histórico vazio para tarefas não concluídas + ]); + } + + dd($receiveAllTasksHistiory); + + //recebe normalmente, porem os checkbox nao conseguem buscar valor, execepto o ultimo dado. + + return view('projectsClients.showAmbitDetailProjectHistory', compact('receiveComments', 'equipmentStatus', 'detailsProject', 'receiveAmbit', 'receiveAllTasksHistiory', 'detalsEquipment', 'detailsEquipmentWorkProject')); } @@ -427,7 +467,7 @@ public function projectDetails_11($projectID, $equipmentID) $filteredTasks = $filteredTasks->map(function ($task) use ($elementalTasksDetails, $DetailsTasks) { // Primeiro bloco: Adiciona detalhes da tarefa elemental - if (isset ($elementalTasksDetails[$task->elemental_tasks_id])) { + if (isset($elementalTasksDetails[$task->elemental_tasks_id])) { $elementalTaskDetail = $elementalTasksDetails[$task->elemental_tasks_id]; $task->elemental_tasks_code = $elementalTaskDetail->elemental_tasks_code; $task->elemental_tasks_description = $elementalTaskDetail->elemental_tasks_description; @@ -450,8 +490,6 @@ public function projectDetails_11($projectID, $equipmentID) return $task; }); - - // Para buscar a tarefa com execution_order = 3 $taskBeforeExecutionOrder = OrderEquipmentTasks::where('equipmentWorkHistorys_id', $receiveEquipmentWorkHistorys->equipmentWorkHistorys_id) ->where('execution_order', 3) @@ -483,9 +521,10 @@ public function projectDetails_11($projectID, $equipmentID) foreach ($specificAttributes as $attribute) { $specificAttributesArray[$attribute->general_attributes_equipment_id] = $attribute->specific_attributes_value; } - // vou te achar cabrao. + //filteredTasks', 'OrdemTasks', 'DetailsTasks' campos vazios para ISV. - return view('projectsClients.articulated_2_ShowEquipment', compact( 'detailsProject', 'dataEquipment', 'filteredTasks', 'OrdemTasks', 'DetailsTasks','specificAttributesArray','receiveEquipmentWorkHistorys')); + + return view('projectsClients.articulated_2_ShowEquipment', compact('detailsProject', 'dataEquipment', 'filteredTasks', 'OrdemTasks', 'DetailsTasks', 'specificAttributesArray', 'receiveEquipmentWorkHistorys')); } //Funcao que recebe a Acoes do dataTables do portifolio. @@ -720,21 +759,24 @@ public function receiveWorkstationProject($receiveNumberProject) public function changeEquipmentStatusOnProject(Request $request) { - $receivedetailsUser = auth()->user(); - $detailsEquipmentWorkHistory = EquipmentWorkHistory:: - where('equipment_id', $request->equipmentID) + $detailsEquipmentWorkHistory = EquipmentWorkHistory::where('equipment_id', $request->equipmentID) ->where('company_projects_id', $request->projectID) - ->where('equipment_status_project', 1) + ->whereIn('equipment_status_project', [1, 4]) ->first(); if ($request->choiseAdminForEquipment == 'approve') { //Se for aprovado, libera o equipamento para relatorio. $detailsEquipmentWorkHistory->equipment_status_project = 2; - $detailsEquipmentWorkHistory->save(); + } else { + // Se nao for aprovado, o equipamento fica para revisão + $detailsEquipmentWorkHistory->equipment_status_project = 4; + } + $detailsEquipmentWorkHistory->save(); + //Sempre vai criar o comentario, a diferenca a se o equipamento tem status : 2 o comanterio vai para o relatorio,se nao vai para os comentarios da Ws. $createCommet = new EquipmentComment; $createCommet->equipmentWorkHistorys_id = $detailsEquipmentWorkHistory->equipmentWorkHistorys_id; @@ -744,12 +786,18 @@ public function changeEquipmentStatusOnProject(Request $request) $createCommet->comment = $request->comment; $createCommet->save(); - return redirect()->route('ExecutionProject', ['projectID' => $request->projectID]) - ->with('success', 'Equipamento aprovado, liberado para relatório.'); + if ($detailsEquipmentWorkHistory->equipment_status_project == 2) { + return redirect()->route('ExecutionProject', ['projectID' => $request->projectID]) + ->with('success', 'Equipamento aprovado, liberado para relatório.'); + } else { + return redirect()->route('ExecutionProject', ['projectID' => $request->projectID]) + ->with('success', 'Equipamento Não aprovado, Enviado para revisar.'); + } } - public function createComment(Request $request){ + public function createComment(Request $request) + { auth()->user(); $newComment = new EquipmentComment; @@ -763,7 +811,8 @@ public function createComment(Request $request){ return back(); } - public function equipmentTaskDetailsPdf(){ + public function equipmentTaskDetailsPdf() + { return view('projectsClients.pdf.equipmentTaskDetailsPdf'); } diff --git a/app/Http/Controllers/WorkstationsJobsController.php b/app/Http/Controllers/WorkstationsJobsController.php index 2d3d6b5c..5a55afb3 100755 --- a/app/Http/Controllers/WorkstationsJobsController.php +++ b/app/Http/Controllers/WorkstationsJobsController.php @@ -80,45 +80,42 @@ public function receiveQuestionsEquipment($equipmentID) } - // public function closeSession(Request $request, $controlEquipmentId) - // { - // $controlEquipment = ControlEquipmentWorkstation::find($controlEquipmentId); - // if ($controlEquipment) { - // $controlEquipment->status = 0; // Marca a sessão como inativa - // $controlEquipment->save(); - - // return response()->json(['success' => true, 'message' => 'Sessão fechada com sucesso.']); - // } - - // return response()->json(['success' => false, 'message' => 'Equipamento não encontrado.']); - // } + + public function receiveAnswersEquipment(Request $request, $control_equipment_workstation_id) { + // dd($request); //No request recebemos ID(NUmero da tarela elementar) , esta variavel vai receber este ID apos selerar o id da string - $elementalTaskID = 0; - + // $elementalTaskID = 0; // Deve receber as perguntas e respostas para a tarefa selecionada $requestData = $request->all(); + // Verifica se há pelo menos um campo que começa com 'ID' + $hasIDKey = false; foreach ($requestData as $key => $value) { - // Verifica se a chave começa com 'ID' if (preg_match('/ID(\d+)/', $key, $matches)) { - // $matches[1] conterá o número após 'ID' + $hasIDKey = true; $elementalTaskID = intval($matches[1]); break; // Sai do loop após encontrar o primeiro match } } - //Ele deve criar a associação entre id atual do control + perguntas e respostas - $receiveAnswersElementalTasks = new workstationsTaskAnswers; + + // Se não encontrou nenhuma chave 'ID', redireciona de volta com uma mensagem de erro + if (!$hasIDKey) { + return redirect()->back()->with('danger', 'A última tarefa não foi salva. Respostas incorretas ou irregulares.'); + } + + // Ele deve criar a associação entre id atual do control + perguntas e respostas + $receiveAnswersElementalTasks = new WorkstationsTaskAnswers; $receiveAnswersElementalTasks->control_equipment_workstation_id = $control_equipment_workstation_id; // Inicializando o array que vai armazenar os objetos JSON $answersArray = []; // Array para armazenar as respostas // Iterar sobre o array externo - foreach ($request->all() as $idKey => $subArray) { + foreach ($requestData as $idKey => $subArray) { // Verificar se a chave atual é uma das chaves de ID (ID1, ID2, etc.) if (strpos($idKey, 'ID') === 0 && is_array($subArray)) { // Iterar sobre o array interno @@ -151,6 +148,7 @@ public function receiveAnswersEquipment(Request $request, $control_equipment_wor // Busca a Ws com base no id recebido da tabela Control. $receiveDataControlWs = ControlEquipmentWorkstation::find($control_equipment_workstation_id); + $receiveDataControlWs->elemental_tasks_id = $elementalTaskID; $receiveDataControlWs->departure_date = now(); @@ -171,32 +169,6 @@ public function receiveAnswersEquipment(Request $request, $control_equipment_wor $receiveDataControlWs->save(); $receiveAnswersElementalTasks->save(); - // dd($recebeDataControlWs); - - // $imagesBase64 = json_decode($request->capturedImages); - // $imagePaths = []; - - // // Assume $receiveDataControlWs já está definido/obtido em algum lugar do seu código - // $folderName = $receiveDataControlWs->control_equipment_workstation_id . '_' . $receiveDataControlWs->equipmentWorkHistorys_id; - - // // Cria a pasta se não existir - // $path = 'receiveImagesControlEquipmentWorkstation/' . $folderName; - // Storage::disk('public')->makeDirectory($path); - - // foreach ($imagesBase64 as $index => $imageBase64) { - // list($type, $imageBase64) = explode(';', $imageBase64); - // list(, $imageBase64) = explode(',', $imageBase64); - // $imageData = base64_decode($imageBase64); - - // // Define um nome de arquivo baseado no índice - // $fileName = $path . '/img' . ($index + 1) . '.png'; - - // // Salva a imagem - // Storage::disk('public')->put($fileName, $imageData); - - // // Armazena o caminho da imagem no array - // $imagePaths[] = $fileName; - // } if ($request->capturedImages) { $imagesBase64 = json_decode($request->capturedImages); $imagePaths = []; @@ -237,20 +209,6 @@ public function receiveAnswersEquipment(Request $request, $control_equipment_wor $model->save(); } - - // return response()->json(['success' => true]); - - - - // Agora que guardamos os dados anteriores, vamos criar a nova linha na tabela Control Equipment ID para que o equipamento continue - // $newControlEquipment = new ControlEquipmentWorkstation; - // $newControlEquipment->equipmentWorkHistorys_id = $recebeDataControlWs->equipmentWorkHistorys_id; - // $newControlEquipment->last_active_at = now(); - // $newControlEquipment->status = 0; - // $newControlEquipment->save(); - - // dd($newControlEquipment); - // Vamos buscar os dados da tarefa elementar comcluida para mandar uma mensagem ao Front e indicar que esta completada $receiveDataElementalTask = ElementalTasks::find($receiveDataControlWs->elemental_tasks_id, 'elemental_tasks_id')->first(); @@ -273,11 +231,16 @@ public function getEquipmentData($equipment_id, $component_tag) $tagType = explode('@', $component_tag)[1]; // Isola o tipo da tag após o '@' - // Recebe o id do Historico do equipamento, em sua obra atual + + // Busca os dados do equipamento $receiveEquipmentWorkHistory = EquipmentWorkHistory::where('equipment_id', $receiveDataEquipment->equipment_id) ->where('company_projects_id', $receiveDataEquipment->company_projects_id) ->first(); + if ($receiveEquipmentWorkHistory && $receiveEquipmentWorkHistory->equipment_status_project == 2) { + return redirect()->back()->with('danger', 'O equipamento já está concluído'); + } + $equipmentInUse = ControlEquipmentWorkstation::where('equipmentWorkHistorys_id', $receiveEquipmentWorkHistory->equipmentWorkHistorys_id) ->whereNull('departure_date') // A data de saída deve ser nula, indicando que a tarefa ainda está ativa ->whereNotNull('id_workstations') // Deve ter um posto de trabalho associado @@ -444,7 +407,7 @@ public function getEquipmentData($equipment_id, $component_tag) ->whereNotNull('departure_date') ->orderByDesc('departure_date') // Ordena por departure_date de forma decrescente ->first(); - + if ($controlEquipment) { // Se encontrar, atribuir control_equipment_workstation_id $task->control_equipment_workstation_id = $controlEquipment->control_equipment_workstation_id; @@ -538,8 +501,6 @@ public function getEquipmentData($equipment_id, $component_tag) return $comment; }); - // dd($recebeTasksForEquipment); - return view('workstations.workstations', [ // Deve receber o atual COntrol ID ? tudo a vez que atualizar ?? diff --git a/app/Http/ViewComposers/WorkstationComposer copy.php b/app/Http/ViewComposers/WorkstationComposer copy.php index b2bcbb96..dda0b074 100755 --- a/app/Http/ViewComposers/WorkstationComposer copy.php +++ b/app/Http/ViewComposers/WorkstationComposer copy.php @@ -24,127 +24,7 @@ public function compose(View $view) $receiveDataEmail = User::where('email', $userEmail)->first(); $receiveDataWs = ConstructionWorkstation::where('name_workstations', $receiveDataEmail->user_name)->first(); - - - - - - // Busca todos os equipamentos associados a um determinado projeto. - // $receiveAllEquipmentOfProject = Equipment::where('company_projects_id', $receiveDataWs->company_projects_id) - // ->whereDoesntHave('equipmentWorkHistory.controlEquipmentWorkstation', function ($query) use ($excludedEquipmentsQuery) { - // //Quarto filtro : Com base na variavel $excludedEquipmentsQuery que serve para excluir equipamentos PSV, quando tem o @Corpo e @Obturador sendo feito em simultanio. - // $query->whereIn('equipmentWorkHistorys_id', $excludedEquipmentsQuery); - // // Primeiro filtro: Equipamentos sem ocorrência em ControlEquipmentWorkstation - // $query->whereDoesntHave('equipmentWorkHistory.controlEquipmentWorkstation'); - // // Segundo filtro: Equipamentos que ja tiverem um controlEquipmentWorkstation_ID criado uma dos Ws o fechou sem concluir por um metodo nao convencional e o script do servidor limpou o controlEquipmentWorkstation_ID - // $query->orWhereHas('equipmentWorkHistory.controlEquipmentWorkstation', function ($subQuery) { - // $subQuery->whereNull('id_workstations') - // ->whereNull('elemental_tasks_id') - // ->whereNull('departure_date') - // ->where('status', 0); - // }); - // // Terceiro filtro: Equipamentos com todas as colunas sao prenchidas como deve ser, signifca que e uma tarefa concluida(finalizada) e agora vai criar um novo dado na controlEquipmentWorkstation para a proxima tarefa. - // $query->orWhereHas('equipmentWorkHistory.controlEquipmentWorkstation', function ($subQuery) { - // $subQuery->whereNotNull('id_workstations') - // ->where(function ($innerQuery) { - // $innerQuery->whereNotNull('elemental_tasks_id') - // ->whereNotNull('departure_date') - // ->where('status', 1); - // }); - // }); - // }) - // // Adiciona condição para PSV (equipment_type_id = 3) - // ->orWhere(function ($query) use ($receiveDataWs) { - // // Verifica no sistema se for uma 'PSV' , mesmo apos entrar como @Corpo, ou pelo @Obutador deve deixar o outro disponivel. - // $query->whereHas('equipmentType', function ($typeQuery) { - // $typeQuery->where('equipment_type_id', 3); - // }) - // ->whereHas('equipmentWorkHistory.controlEquipmentWorkstation', function ($subQuery) { - // $subQuery->where('status', 1) - // ->whereNull('departure_date') - // ->where(function ($taskQuery) { - // $taskQuery->where('elemental_tasks_id', 9) - // ->orWhereNull('elemental_tasks_id'); - // }); - // }); - // }) - // ->with([ - // 'equipmentWorkHistory' => function ($query) use ($receiveDataWs) { - // $query->where('company_projects_id', $receiveDataWs->company_projects_id) - // ->select('equipment_id', 'equipmentWorkHistorys_id'); - // } - // ]) - // ->get() - // ->map(function ($equipment) { - // if (!$equipment->equipmentWorkHistory->isEmpty()) { - // $equipmentWorkHistory = $equipment->equipmentWorkHistory->first(); - // $equipment->equipmentWorkHistoryId = $equipmentWorkHistory->equipmentWorkHistorys_id; - // } else { - // $equipment->equipmentWorkHistoryId = null; - // } - // return $equipment; - // }); - - - - - - - // foreach ($receiveAllEquipmentOfProject as $equipment) { - // // Agora 'equipmentWorkHistoryId' contém um único ID, então não usamos 'pluck' - // $workHistoryId = $equipment->equipmentWorkHistoryId; // Obter ID do histórico de trabalho diretamente - - // // Verifica se existe um workHistoryId antes de prosseguir - // if (is_null($workHistoryId)) { - // continue; // Se não houver histórico de trabalho, continua para o próximo equipamento - // } - - // $taskIds = OrderEquipmentTasks::where('equipmentWorkHistorys_id', $workHistoryId) - // ->pluck('elemental_tasks_id'); // Obter IDs de tarefas elementares baseado em um único workHistoryId - - // if ($taskIds->isEmpty()) { - // continue; // Se não houver tarefas, continua para o próximo equipamento - // } - - // //ESTE Code ve quantas vezes ja foi realizada cada tarefa do equipamento atual, saber o code a baixo ver se falta muito ou ja esta quase a acaber - // $workstationTaskCounts = ControlEquipmentWorkstation::whereIn('elemental_tasks_id', $taskIds) - // ->select('elemental_tasks_id', DB::raw('count(*) as total')) - // ->groupBy('elemental_tasks_id') - // ->pluck('total', 'elemental_tasks_id'); // Contagem de tarefas nas estações de trabalho - - // // Verificar se todas as tarefas foram concluídas pelo menos uma vez - // $allTasksCompleted = $taskIds->every(function ($taskId) use ($workstationTaskCounts) { - // return isset ($workstationTaskCounts[$taskId]) && $workstationTaskCounts[$taskId] >= 1; - // }); - - // if ($allTasksCompleted && $workstationTaskCounts->count() >= $taskIds->count()) { - // $completedEquipments->push($equipment); // Adicionar equipamento à lista de concluídos - // } - // } - - // // Remover equipamentos concluídos da coleção original - // $receiveAllEquipmentOfProject = $receiveAllEquipmentOfProject->reject(function ($equipment) use ($completedEquipments) { - // return $completedEquipments->contains($equipment); - // }); - - // $equipmentIds = $receiveAllEquipmentOfProject->pluck('equipment_id'); - - // $receiveQrcodeEquipmentsProject = QrcodesAssociatedEquipment::whereIn('equipment_id', $equipmentIds)->get(); - - // //VAMOS filtrar os valores recebidos e terar todas as correspondencias de Flange, ja nao e uma tag que nao vai entrar no percurso do Equipamento. - // $filteredQrcodeEquipments = $receiveQrcodeEquipmentsProject->reject(function ($item) { - // return strpos($item->component_tag, '@Flange') !== false; - // }); - - - - - - - - - - + // Busca todos os equipamentos associados a um determinado projeto. // Este código identifica equipmentWorkHistorys_id que estão simultaneamente envolvidos em duas tarefas // (uma identificada por elemental_tasks_id = 9 e elemental_tasks_id = NULL), quando o departure_date é null) ou seja, ainda em progresso... @@ -170,7 +50,7 @@ public function compose(View $view) ->whereNull('entry_date') ->where('status', 0); }) - // Condicao 2 : Se os dados encontrados do equipamento tiverem com o departure_date principalmente diferente de NUll, signica que o ultima dado deste equipamento fez e concluiu uma de suas tarefas e agora precisa criar um dado novo. + // Condicao 2 : Se os dados encontrados do equipamento tiverem com o departure_date principalmente diferente de NUll, signica que o ultimo dado deste equipamento fez e concluiu uma de suas tarefas e agora precisa criar um dado novo. ->orWhereHas('equipmentWorkHistory.controlEquipmentWorkstation', function ($subQuery) { $subQuery->whereNotNull('id_workstations') ->where(function ($innerQuery) { @@ -194,12 +74,15 @@ public function compose(View $view) return $equipment; }); + $equipmentToReview = collect(); // Coleção para armazenar equipamentos para revisão + $completedEquipments = collect(); // Coleção para armazenar equipamentos concluídos // Inicializa um array para armazenar o status de cada equipamento $equipmentStatus = []; foreach ($receiveAllEquipmentOfProject as $equipment) { + // Agora 'equipmentWorkHistoryId' contém um único ID, então não usamos 'pluck' $workHistoryId = $equipment->equipmentWorkHistoryId; // Obter ID do histórico de trabalho diretamente diff --git a/app/Http/ViewComposers/WorkstationComposer.php b/app/Http/ViewComposers/WorkstationComposer.php index ccf65e8f..b4d213f4 100755 --- a/app/Http/ViewComposers/WorkstationComposer.php +++ b/app/Http/ViewComposers/WorkstationComposer.php @@ -82,7 +82,7 @@ public function compose(View $view) ->where('status', 0); }); }) - ->with('equipmentWorkHistory') // Carrega o relacionamento equipmentWorkHistory + ->with('equipmentWorkHistory') // Carrega o relacionamento equipmentWorkHistory a coleção de cada equipamento ->get() ->map(function ($equipment) { if (!$equipment->equipmentWorkHistory->isEmpty()) { @@ -94,6 +94,8 @@ public function compose(View $view) return $equipment; }); + $equipmentToReview = collect(); // Coleção para armazenar equipamentos para revisão + $completedEquipments = collect(); // Coleção para armazenar equipamentos concluídos // Inicializa um array para armazenar o status de cada equipamento @@ -151,10 +153,38 @@ public function compose(View $view) } } - $workstationTaskCounts = ControlEquipmentWorkstation::whereIn('elemental_tasks_id', $taskIds) - ->select('elemental_tasks_id', DB::raw('count(*) as total')) - ->groupBy('elemental_tasks_id') - ->pluck('total', 'elemental_tasks_id'); // Contagem de tarefas nas estações de trabalho + + // $workstationTaskCounts = ControlEquipmentWorkstation::whereIn('elemental_tasks_id', $taskIds) + // ->select('elemental_tasks_id', DB::raw('count(*) as total')) + // ->groupBy('elemental_tasks_id') + // ->pluck('total', 'elemental_tasks_id'); // Contagem de tarefas nas estações de trabalho + + + // Vai verificar diretamente na base de dados , busca todos os dados do equipmentWorkHistorys_id, nesta obra e verificar com base na colecao recebida, se entre todos os seus valores, tem pelo menos um elemental_tasks_id, presente na variavel $taskIds + // $taskCountsInControlRecords = ControlEquipmentWorkstation::where('equipmentWorkHistorys_id', $workHistoryId) + // ->whereNotNull('departure_date') + // ->whereIn('elemental_tasks_id', $taskIds) + // ->groupBy('elemental_tasks_id') + // ->select('elemental_tasks_id', DB::raw('COUNT(*) as count')) + // ->pluck('count', 'elemental_tasks_id'); + + // // Verifica se todas as tarefas foram concluídas pelo menos uma vez + // $allTasksCompleted = $taskIds->every(function ($taskId) use ($taskCountsInControlRecords) { + // return isset ($taskCountsInControlRecords[$taskId]) && $taskCountsInControlRecords[$taskId] > 0; + // }); + + // //$allTasksCompleted vai ter TRUE, apenas quando se verificar todos as tarefas foram feitas no equipamento. + // if ($allTasksCompleted) { + // $changeEquipmentStatus = EquipmentWorkHistory::where('equipmentWorkHistorys_id', $equipment->equipmentWorkHistoryId)->first(); + + // if ($changeEquipmentStatus->equipment_status_project == 2) { + // $completedEquipments->push($equipment); + // $changeEquipmentStatus->equipment_status_project = 1; + // $changeEquipmentStatus->save(); + // } elseif ($changeEquipmentStatus->equipment_status_project == 4) { + // $equipmentToReview->push($equipment); + // } + // } // Vai verificar diretamente na base de dados , busca todos os dados do equipmentWorkHistorys_id, nesta obra e verificar com base na colecao recebida, se entre todos os seus valores, tem pelo menos um elemental_tasks_id, presente na variavel $taskIds $taskCountsInControlRecords = ControlEquipmentWorkstation::where('equipmentWorkHistorys_id', $workHistoryId) @@ -166,24 +196,49 @@ public function compose(View $view) // Verifica se todas as tarefas foram concluídas pelo menos uma vez $allTasksCompleted = $taskIds->every(function ($taskId) use ($taskCountsInControlRecords) { - return isset ($taskCountsInControlRecords[$taskId]) && $taskCountsInControlRecords[$taskId] > 0; + return isset($taskCountsInControlRecords[$taskId]) && $taskCountsInControlRecords[$taskId] > 0; }); - //$allTasksCompleted vai ter TRUE, apenas quando se verificar todos as tarefas foram feitas no equipamento. + // $allTasksCompleted vai ter TRUE, apenas quando se verificar todos as tarefas foram feitas no equipamento. if ($allTasksCompleted) { - $completedEquipments->push($equipment); + $changeEquipmentStatus = EquipmentWorkHistory::where('equipmentWorkHistorys_id', $equipment->equipmentWorkHistoryId)->first(); - //Se o equipamento for verificado como concluido, altera o seu status na Obra, para o mesmo ser indicado como um equipamento pendente a aplovacao de Admin. - $changeEquipmentStatus = EquipmentWorkHistory::where('equipmentWorkHistorys_id',$equipment->equipmentWorkHistoryId)->first(); - $changeEquipmentStatus->equipment_status_project = 1; - $changeEquipmentStatus->save(); + if ($changeEquipmentStatus->equipment_status_project == 0) { + $changeEquipmentStatus->equipment_status_project = 1; + $changeEquipmentStatus->save(); + } elseif ($changeEquipmentStatus->equipment_status_project == 2) { + $completedEquipments->push($equipment); + } elseif ($changeEquipmentStatus->equipment_status_project == 4) { + $equipmentToReview->push($equipment); + } } + + + // Remover equipamentos concluídos da coleção original + $receiveAllEquipmentOfProject = $receiveAllEquipmentOfProject->reject(function ($equipment) use ($completedEquipments) { + return $completedEquipments->contains($equipment); + }); + + + // Remover equipamentos a serem revisados da coleção original + $receiveAllEquipmentOfProject = $receiveAllEquipmentOfProject->reject(function ($equipment) use ($equipmentToReview) { + return $equipmentToReview->contains($equipment); + }); + + // if ($allTasksCompleted) { + // $completedEquipments->push($equipment); + + // //Se o equipamento for verificado como concluido, altera o seu status na Obra, para o mesmo ser indicado como um equipamento pendente a aplovacao de Admin. + // $changeEquipmentStatus = EquipmentWorkHistory::where('equipmentWorkHistorys_id',$equipment->equipmentWorkHistoryId)->first(); + // $changeEquipmentStatus->equipment_status_project = 1; + // $changeEquipmentStatus->save(); + // } } - + // Remover equipamentos concluídos da coleção original - $receiveAllEquipmentOfProject = $receiveAllEquipmentOfProject->reject(function ($equipment) use ($completedEquipments) { - return $completedEquipments->contains($equipment); - }); + // $receiveAllEquipmentOfProject = $receiveAllEquipmentOfProject->reject(function ($equipment) use ($completedEquipments) { + // return $completedEquipments->contains($equipment); + // }); $equipmentIds = array_keys($equipmentStatus); @@ -224,13 +279,13 @@ public function compose(View $view) return true; } }); - //Returning values of the queries to workstations layout $view->with([ 'receiveAllEquipmentOfProject' => $receiveAllEquipmentOfProject, // foi alterado para a variavel 'filteredQrcodeEquipments' pois nao tem a necessidade do utilizador selecionar 'Flange'(AINDA NAO !) 'receiveQrcodeEquipmentsProject' => $filteredQrcodeEquipments, 'completedEquipments' => $completedEquipments, + 'equipmentToReview' => $equipmentToReview, 'receiveDataWs' => $receiveDataWs, ]); diff --git a/app/Services/PdfWrapper.php b/app/Services/PdfWrapper.php index 81076b0a..c6f73bdf 100644 --- a/app/Services/PdfWrapper.php +++ b/app/Services/PdfWrapper.php @@ -1,75 +1,310 @@ pdfGenerator = new Browsershot(); +// $this->headerHtml = view('projectsClients.pdf._header')->render(); +// $this->footerHtml = view('projectsClients.pdf._footer')->render(); +// } +// // Load view and render HTML +// public function loadView(string $bladeFile, array $data = []): self +// { +// $this->html = view($bladeFile, $data)->render(); +// return $this; +// } +// // Load raw HTML +// public function loadHtml(string $html): self +// { +// $this->html = $html; +// return $this; +// } +// // Load HTML from a URL +// public function loadUrl(string $url): self +// { +// $this->html = file_get_contents(url($url)); +// return $this; +// } +// // Generate the PDF using Browsershot +// public function generate(): Browsershot +// { +// return $this->pdfGenerator +// ->html($this->html) +// ->format('A4') +// ->margins(10, 20, 10, 20) +// ->showBrowserHeaderAndFooter() +// ->headerHtml($this->headerHtml) +// ->footerHtml($this->footerHtml) +// ->waitUntilNetworkIdle(); +// } +// // Save the PDF to the server in the public folder +// public function save(string $path): void +// { +// $this->generate()->savePdf($path); +// } +// // Download the PDF with a specified filename +// public function download(string $filename) +// { +// $pdf = $this->generate()->pdf(); +// return new Response($pdf, 200, [ +// 'Content-Type' => 'application/pdf', +// 'Content-Disposition' => 'attachment; filename="'.$filename.'"', +// 'Content-Length' => strlen($pdf) +// ]); +// } +// // Stream the PDF in the browser +// public function stream(string $filename) +// { +// $pdf = $this->generate()->pdf(); +// return new Response($pdf, 200, [ +// 'Content-Type' => 'application/pdf', +// 'Content-Disposition' => 'inline; filename="'.$filename.'"' +// ]); +// } +// } + + +// namespace App\Services; +// use Spatie\Browsershot\Browsershot; +// use Illuminate\Http\Response; +// class PdfWrapper +// { +// protected Browsershot $pdfGenerator; +// protected string $html; +// public function __construct() +// { +// $this->pdfGenerator = new Browsershot(); +// } +// // Load view and render HTML +// public function loadView(string $bladeFile, array $data = []): self +// { +// $this->html = view($bladeFile, $data)->render(); +// return $this; +// } +// // Load raw HTML +// public function loadHtml(string $html): self +// { +// $this->html = $html; +// return $this; +// } +// // Load HTML from a URL +// public function loadUrl(string $url): self +// { +// $this->html = file_get_contents(url($url)); +// return $this; +// } +// // Generate the PDF using Browsershot +// public function generate(): Browsershot +// { +// return $this->pdfGenerator +// ->html($this->html) +// ->format('A4') +// // ->margins(10, 10, 10, 10) +// ->scale(0.7) +// ->fullPage() +// ->setOption('printBackground',true) +// ->waitUntilNetworkIdle(); +// } +// // Save the PDF to the server in the public folder +// public function save(string $path): void +// { +// $this->generate()->savePdf($path); +// } +// // Download the PDF with a specified filename +// public function download(string $filename) +// { +// $pdf = $this->generate()->pdf(); +// return new Response($pdf, 200, [ +// 'Content-Type' => 'application/pdf', +// 'Content-Disposition' => 'attachment; filename="'.$filename.'"', +// 'Content-Length' => strlen($pdf) +// ]); +// } +// // Stream the PDF in the browser +// public function stream(string $filename) +// { +// $pdf = $this->generate()->pdf(); +// return new Response($pdf, 200, [ +// 'Content-Type' => 'application/pdf', +// 'Content-Disposition' => 'inline; filename="'.$filename.'"' +// ]); +// } +// } + + + +// namespace App\Services; + +// use Spatie\Browsershot\Browsershot; +// use Illuminate\Http\Response; +// use Illuminate\Support\Facades\File; + +// class PdfWrapper +// { +// protected Browsershot $pdfGenerator; +// protected string $html; + +// public function __construct() +// { +// $this->pdfGenerator = new Browsershot(); +// } + +// // Load view and render HTML +// public function loadView(string $bladeFile, array $data = []): self +// { +// // Convert image paths to base64 +// if (isset($data['imagePaths']) && is_array($data['imagePaths'])) { +// $data['imagesBase64'] = array_map(function($path) { +// return $this->getImageBase64($path); +// }, $data['imagePaths']); +// } + +// $this->html = view($bladeFile, $data)->render(); +// return $this; +// } + +// // Load raw HTML +// public function loadHtml(string $html): self +// { +// $this->html = $html; +// return $this; +// } + +// // Load HTML from a URL +// public function loadUrl(string $url): self +// { +// $this->html = file_get_contents(url($url)); +// return $this; +// } + +// // Generate the PDF using Browsershot +// public function generate(): Browsershot +// { +// return $this->pdfGenerator +// ->html($this->html) +// ->format('A4') +// ->scale(0.7) +// ->fullPage() +// ->setOption('printBackground', true) +// ->waitUntilNetworkIdle(); +// } + +// // Save the PDF to the server in the public folder +// public function save(string $path): void +// { +// $this->generate()->savePdf($path); +// } + +// // Download the PDF with a specified filename +// public function download(string $filename) +// { +// $pdf = $this->generate()->pdf(); +// return new Response($pdf, 200, [ +// 'Content-Type' => 'application/pdf', +// 'Content-Disposition' => 'attachment; filename="'.$filename.'"', +// 'Content-Length' => strlen($pdf) +// ]); +// } + +// // Stream the PDF in the browser +// public function stream(string $filename) +// { +// $pdf = $this->generate()->pdf(); +// return new Response($pdf, 200, [ +// 'Content-Type' => 'application/pdf', +// 'Content-Disposition' => 'inline; filename="'.$filename.'"' +// ]); +// } + +// // Function to convert image to base64 +// protected function getImageBase64($imagePath) +// { +// $path = public_path($imagePath); +// $type = pathinfo($path, PATHINFO_EXTENSION); +// $data = File::get($path); +// $base64 = 'data:image/' . $type . ';base64,' . base64_encode($data); + +// return $base64; +// } +// } + + + namespace App\Services; + use Spatie\Browsershot\Browsershot; use Illuminate\Http\Response; +use Illuminate\Support\Facades\File; -class PdfWrapper { - +class PdfWrapper +{ protected Browsershot $pdfGenerator; - protected string $html; - protected string $headerHtml; - - protected string $footerHtml; - - public function __construct() { - + public function __construct() + { $this->pdfGenerator = new Browsershot(); - - $this->headerHtml = view('projectsClients.pdf._header')->render(); - - $this->footerHtml = view('projectsClients.pdf._footer')->render(); - } - //Load views - public function loadView(string $bladeFile, array $data = []): self { - - $this -> html = view($bladeFile, $data)->render(); + // Load view and render HTML + public function loadView(string $bladeFile, array $data = []): self + { + // Convert image paths to base64 + if (isset($data['imagePaths']) && is_array($data['imagePaths'])) { + $data['imagesBase64'] = array_map(function($path) { + return $this->getImageBase64($path); + }, $data['imagePaths']); + } + $this->html = view($bladeFile, $data)->render(); return $this; } - //Load HTML - public function loadHtml(string $html): self { - - $this -> html = $html; - + // Load raw HTML + public function loadHtml(string $html): self + { + $this->html = $html; return $this; } - public function loadUrl(string $url): self { - - $this -> html = url($url); - + // Load HTML from a URL + public function loadUrl(string $url): self + { + $this->html = file_get_contents(url($url)); return $this; } - - //Function to generate PDFs - public function generate(): Browsershot { + + // Generate the PDF using Browsershot + public function generate(): Browsershot + { return $this->pdfGenerator - ->html($this->html) - ->format('A4') - ->margins(10, 20, 10, 20) - ->showBrowserHeaderAndFooter() - ->headerHtml($this->headerHtml) - ->footerHtml($this->footerHtml) - ->waitUntilNetworkIdle(); + ->html($this->html) + ->format('A4') + ->scale(0.7) + ->fullPage() + ->setOption('printBackground', true) + ->showBackground() + ->waitUntilNetworkIdle(); } - //Function to save to server in public folder - public function save(string $path): void { + // Save the PDF to the server in the public folder + public function save(string $path): void + { $this->generate()->savePdf($path); } - //Function to save the PDF to client with specific filename - public function download(string $filename) { - - + // Download the PDF with a specified filename + public function download(string $filename) + { $pdf = $this->generate()->pdf(); - return new Response($pdf, 200, [ 'Content-Type' => 'application/pdf', 'Content-Disposition' => 'attachment; filename="'.$filename.'"', @@ -77,14 +312,24 @@ public function download(string $filename) { ]); } - //Function to view PDF in browser - public function stream(string $filename) { - + // Stream the PDF in the browser + public function stream(string $filename) + { $pdf = $this->generate()->pdf(); - return new Response($pdf, 200, [ 'Content-Type' => 'application/pdf', 'Content-Disposition' => 'inline; filename="'.$filename.'"' ]); } -} \ No newline at end of file + + // Function to convert image to base64 + protected function getImageBase64($imagePath) + { + $path = public_path($imagePath); + $type = pathinfo($path, PATHINFO_EXTENSION); + $data = File::get($path); + $base64 = 'data:image/' . $type . ';base64,' . base64_encode($data); + + return $base64; + } +} diff --git a/public/receiveImagesControlEquipmentWorkstation/1897_3781/img1.png b/public/receiveImagesControlEquipmentWorkstation/1897_3781/img1.png new file mode 100644 index 00000000..556529ae Binary files /dev/null and b/public/receiveImagesControlEquipmentWorkstation/1897_3781/img1.png differ diff --git a/public/receiveImagesControlEquipmentWorkstation/1897_3781/img2.png b/public/receiveImagesControlEquipmentWorkstation/1897_3781/img2.png new file mode 100644 index 00000000..4d92f4d8 Binary files /dev/null and b/public/receiveImagesControlEquipmentWorkstation/1897_3781/img2.png differ diff --git a/public/receiveImagesControlEquipmentWorkstation/1897_3781/img3.png b/public/receiveImagesControlEquipmentWorkstation/1897_3781/img3.png new file mode 100644 index 00000000..312eeeec Binary files /dev/null and b/public/receiveImagesControlEquipmentWorkstation/1897_3781/img3.png differ diff --git a/public/receiveImagesControlEquipmentWorkstation/1926_3781/img1.png b/public/receiveImagesControlEquipmentWorkstation/1926_3781/img1.png new file mode 100644 index 00000000..a2a72360 Binary files /dev/null and b/public/receiveImagesControlEquipmentWorkstation/1926_3781/img1.png differ diff --git a/public/receiveImagesControlEquipmentWorkstation/1926_3781/img2.png b/public/receiveImagesControlEquipmentWorkstation/1926_3781/img2.png new file mode 100644 index 00000000..f59096be Binary files /dev/null and b/public/receiveImagesControlEquipmentWorkstation/1926_3781/img2.png differ diff --git a/public/receiveImagesControlEquipmentWorkstation/1926_3781/img3.png b/public/receiveImagesControlEquipmentWorkstation/1926_3781/img3.png new file mode 100644 index 00000000..b827e7eb Binary files /dev/null and b/public/receiveImagesControlEquipmentWorkstation/1926_3781/img3.png differ diff --git a/resources/views/Templates/templateWorkstations.blade.php b/resources/views/Templates/templateWorkstations.blade.php index cb7645a8..478d4941 100755 --- a/resources/views/Templates/templateWorkstations.blade.php +++ b/resources/views/Templates/templateWorkstations.blade.php @@ -50,6 +50,7 @@