1989 lines
95 KiB
PHP
Executable File
1989 lines
95 KiB
PHP
Executable File
<?php
|
|
|
|
|
|
namespace App\Http\Controllers;
|
|
|
|
use App\Models\AssociationCompanyUser;
|
|
use App\Models\Company;
|
|
use App\Models\EquipmentWorkHistory;
|
|
use App\Models\HistoryOfEquipmentAmbitsInTheProject;
|
|
use App\Models\ProjectExcelLog;
|
|
use Illuminate\Http\Request;
|
|
use Illuminate\Support\Facades\DB;
|
|
|
|
|
|
use Illuminate\Support\Facades\Log;
|
|
|
|
use PhpOffice\PhpSpreadsheet\IOFactory;
|
|
|
|
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
|
|
use Symfony\Component\HttpFoundation\StreamedResponse;
|
|
|
|
|
|
use App\Models\User;
|
|
use App\Models\CompanyProject;
|
|
use App\Models\Unit;
|
|
use App\Models\EquipmentType;
|
|
use App\Models\Equipment;
|
|
use App\Models\Plant;
|
|
use App\Models\SpecificAttributesEquipmentType;
|
|
use App\Models\GeneralAttributesEquipment;
|
|
use App\Models\PendingEquipment;
|
|
use App\Models\AmbitsEquipment;
|
|
use App\Models\EquipmentAssociationAmbit;
|
|
use App\Models\ConstructionWorkstation;
|
|
use App\Models\ElementalTasks;
|
|
use App\Models\OrderEquipmentTasks;
|
|
use App\Models\FurtherTasks;
|
|
use App\Models\WorkstationsAssociationTasks;
|
|
use App\Models\TasksAssociationAmbits;
|
|
use App\Models\QrcodesAssociatedEquipment;
|
|
|
|
use LengthException;
|
|
|
|
// use DataTables;
|
|
|
|
class CreateProjectController extends Controller
|
|
{
|
|
public function changeStateProject($projectId)
|
|
{
|
|
$detailsPrpject = CompanyProject::where('company_projects_id', $projectId)->first();
|
|
$detailsPrpject->order_project = 3;
|
|
$detailsPrpject->save();
|
|
|
|
// Redireciona para a rota 'home' após alterar o estado para execução
|
|
return redirect()->route('home');
|
|
}
|
|
|
|
public function deleteProject($projectId)
|
|
{
|
|
// Encontra o projeto pelo ID
|
|
$deleteProject = CompanyProject::where('company_projects_id', $projectId)->first();
|
|
|
|
if ($deleteProject) {
|
|
// Busca todas as ConstructionWorkstation associadas ao projeto
|
|
$workstations = ConstructionWorkstation::where('company_projects_id', $projectId)->get();
|
|
|
|
foreach ($workstations as $workstation) {
|
|
// Para cada workstation, busca usuários com o mesmo nome
|
|
$user = User::where('user_name', $workstation->name_workstations)->first();
|
|
|
|
if ($user) {
|
|
$user->delete();
|
|
}
|
|
}
|
|
|
|
// Deleta o projeto após processar as workstations
|
|
$deleteProject->delete();
|
|
|
|
// Redireciona para a rota 'home' após a deleção
|
|
return redirect()->route('home');
|
|
}
|
|
|
|
}
|
|
|
|
public function changeAmbitEquipment(Request $request)
|
|
{
|
|
$receiveAmbitEquipmentId = $request->receveAmbit;
|
|
$equipmentId = $request->equipmentID;
|
|
|
|
$receiveEquipment = Equipment::where('equipment_id', $equipmentId)->first();
|
|
|
|
$receiveEquipmentWorkHistorys = EquipmentWorkHistory::where('equipment_id', $receiveEquipment->equipment_id)
|
|
->where('company_projects_id', $receiveEquipment->company_projects_id)
|
|
->first();
|
|
|
|
$receiveDataEquipmentAssociationAmbit = EquipmentAssociationAmbit::where('equipmentWorkHistorys_id', $receiveEquipmentWorkHistorys->equipmentWorkHistorys_id)
|
|
->first();
|
|
|
|
// Se o ambito atual for igual ao antigo ambito
|
|
if ($receiveDataEquipmentAssociationAmbit->ambits_id == $receiveAmbitEquipmentId) {
|
|
return back()->with('danger', 'Âmbito selecionado é igual ao anterior!');
|
|
} else {
|
|
// Verificar se existe um histórico de âmbito sem timestamp (time_change_ambit)
|
|
$existingHistory = HistoryOfEquipmentAmbitsInTheProject::where('equipmentWorkHistorys_id', $receiveEquipmentWorkHistorys->equipmentWorkHistorys_id)
|
|
->where('ambits_id', $receiveDataEquipmentAssociationAmbit->ambits_id)
|
|
->whereNull('time_change_ambit')
|
|
->first();
|
|
|
|
// Se existir e o time_change_ambit for nulo, atualiza com o timestamp atual
|
|
if ($existingHistory) {
|
|
$existingHistory->time_change_ambit = now();
|
|
$existingHistory->save();
|
|
}
|
|
|
|
// Criar um novo registro em HistoryOfEquipmentAmbitsInTheProject para o novo âmbito
|
|
$newHistoryOfEquipmentAmbits = new HistoryOfEquipmentAmbitsInTheProject;
|
|
$newHistoryOfEquipmentAmbits->equipmentWorkHistorys_id = $receiveEquipmentWorkHistorys->equipmentWorkHistorys_id;
|
|
$newHistoryOfEquipmentAmbits->ambits_id = $receiveAmbitEquipmentId;
|
|
$newHistoryOfEquipmentAmbits->time_change_ambit = null; // Novo registro sem timestamp
|
|
$newHistoryOfEquipmentAmbits->save();
|
|
|
|
// 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->inspection = 2; // ou outro valor conforme necessário
|
|
$JoinsEquipmentsWithTasks->save();
|
|
}
|
|
|
|
return back()->with('success', 'Equipamento: ' . $receiveEquipment->equipment_id . ' trocado de âmbito com sucesso!');
|
|
}
|
|
}
|
|
|
|
|
|
public function deleteEquipmentInProject(Request $request)
|
|
{
|
|
$receiveEquipment = Equipment::where('equipment_id', $request->equipmentId)->first();
|
|
$receiveStatus = $request->deleteEquipmentProject;
|
|
|
|
//Independente do tipo de select ele vai deletar o equipamento do Historico
|
|
EquipmentWorkHistory::where('equipment_id', $receiveEquipment->equipment_id)
|
|
->where('company_projects_id', $receiveEquipment->company_projects_id)
|
|
->delete();
|
|
|
|
// Deleta o equipamento por completo e retorna
|
|
if ($receiveStatus == 'complete') {
|
|
$receiveEquipment->delete();
|
|
|
|
return redirect()->back()
|
|
->with('success', 'Equipamento: ' . $receiveEquipment->equipment_id . ' excluído com sucesso!');
|
|
} else {
|
|
// Deleta apaga a associacao do equipamento a Obra
|
|
$receiveEquipment->company_projects_id = null;
|
|
$receiveEquipment->save();
|
|
|
|
return redirect()->back()
|
|
->with('success', 'Equipamento: ' . $receiveEquipment->equipment_id . ' retirado da obra com sucesso!');
|
|
}
|
|
}
|
|
|
|
|
|
|
|
public function deletePendingEquipments(Request $request)
|
|
{
|
|
$pendingEquipmentIds = $request->input('pendingEquipmentIds', []);
|
|
|
|
// Verifica se o array não está vazio
|
|
if (!empty($pendingEquipmentIds)) {
|
|
// Deleta todos os registros de PendingEquipment que correspondam aos IDs
|
|
PendingEquipment::whereIn('pending_equipment_id', $pendingEquipmentIds)->delete();
|
|
}
|
|
|
|
return redirect()->back()
|
|
->with('success', 'Todos os equipamentos pendentes apagados com sucesso!');
|
|
}
|
|
|
|
|
|
public function receiveUnits($numberProject)
|
|
{
|
|
$PlantData = CompanyProject::where('company_projects_id', $numberProject)->first();
|
|
|
|
if (!$PlantData) {
|
|
return response()->json([]);
|
|
}
|
|
|
|
$receiveUnits = Unit::where('plant_id', $PlantData->plant_id)->get();
|
|
|
|
// Formatar a resposta para o formato esperado pelo JavaScript
|
|
$formattedUnits = $receiveUnits->map(function ($unit) {
|
|
return [
|
|
'id' => $unit->receiveUnits, // Ajuste para o nome da sua coluna correta
|
|
'name' => $unit->unit_name // Ajuste para o nome da sua coluna correta
|
|
];
|
|
});
|
|
|
|
return response()->json($formattedUnits);
|
|
}
|
|
|
|
|
|
public function deleteFurtherTasks(Request $request)
|
|
{
|
|
//Se o utilizador click mas nao associar as tarefas.
|
|
$selectedTasks = $request->input('selectedTasks', []);
|
|
|
|
if (empty($selectedTasks)) {
|
|
return back()->with('danger', 'Não existem tarefas complementares selecionadas para exclusão.');
|
|
}
|
|
|
|
$receiveDataEquipment = Equipment::where('equipment_id', $request->equipmentID)->first();
|
|
// Buscar os registros que correspondem ao equipmentID e que têm further_tasks_id nos selectedTasks
|
|
//Nao deve ter mais further_tasks_id, pois agora as further tasks devem ficar nas tarefas elementares
|
|
$detailsEquipmentWorkHistory = EquipmentWorkHistory::where('equipment_id', $request->equipmentID)->first();
|
|
|
|
$tasksToDelete = OrderEquipmentTasks::where('equipmentWorkHistorys_id', $detailsEquipmentWorkHistory->equipmentWorkHistorys_id)
|
|
->whereIn('elemental_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") {
|
|
ElementalTasks::whereIn('elemental_tasks_id', $request->selectedTasks)->delete();
|
|
}
|
|
|
|
// Reordenar os registros restantes
|
|
$remainingTasks = OrderEquipmentTasks::where('equipmentWorkHistorys_id', $detailsEquipmentWorkHistory->equipmentWorkHistorys_id)
|
|
->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 os detalhes do Equipment
|
|
$receiveDataEquipment = Equipment::where('equipment_id', $request->equipmentID)->first();
|
|
|
|
// Recebe os detalhes do EquipmentWorkHistory
|
|
$receiveEquipmentWorkHistory = EquipmentWorkHistory::where('equipment_id', $request->equipmentID)
|
|
->where('company_projects_id', $receiveDataEquipment->company_projects_id)
|
|
->first();
|
|
|
|
//Ordena os valores de OrderEquipmentTasks deste equipamento do Menor para o Maior
|
|
$tasksToReorder = OrderEquipmentTasks::where('equipmentWorkHistorys_id', $receiveEquipmentWorkHistory->equipmentWorkHistorys_id)
|
|
->orderBy('execution_order', 'asc')
|
|
->get();
|
|
|
|
//indica onde vai ficar na nova organizacao das tarefas
|
|
$insertPosition = $request->ArrayListElementsTasks + 1;
|
|
|
|
if ($request->selectedFurtherTaskExisting != 'null') {
|
|
|
|
//Se o $resquest->selectedFurtherTaskExisting nao for null significa que selecionou uma tarefa complementar existente
|
|
//Se for diferente o campo de descricao,, Adicionamos.
|
|
$detailsFutherTaskSelected = ElementalTasks::where('elemental_tasks_id', $request->selectedFurtherTaskExisting)->first();
|
|
$detailsFutherTaskSelected->further_tasks_description = $request->furtherTaskDescription;
|
|
$detailsFutherTaskSelected->save();
|
|
|
|
} else {
|
|
|
|
// Conta o número de registros na ElementalTasks com o company_projects_id especificado
|
|
$count = ElementalTasks::where('company_projects_id', $request->company_projects_id)->count();
|
|
|
|
// Se não existir nenhum registro, define $count como 1
|
|
$count = $count > 0 ? $count : 0;
|
|
|
|
|
|
$maxElementalTaskId = ElementalTasks::max('elemental_tasks_id');
|
|
// Precisa Saber a Obra para ver quantos tarefas Complementares, ja existe para esta Obra
|
|
|
|
// Calcule o valor de further_tasks_name
|
|
$newFurtherTaskName = 'TC' . ($count + 1);
|
|
|
|
|
|
//Cria uma nova Tarefa Complementar
|
|
$newFurtherTask = new ElementalTasks;
|
|
//Ao definir exatamente o numero ao invez de deixar por auto Incremento, quando apagar essas tarefas complementares, ao proximas podem usar o mesmo Id
|
|
$newFurtherTask->elemental_tasks_id = $maxElementalTaskId + 1;
|
|
$newFurtherTask->elemental_tasks_code = $newFurtherTaskName;
|
|
$newFurtherTask->elemental_tasks_description = $request->furtherTask;
|
|
$newFurtherTask->further_tasks_description = $request->furtherTaskDescription;
|
|
$newFurtherTask->company_projects_id = $request->company_projects_id;
|
|
$newFurtherTask->save();
|
|
}
|
|
|
|
|
|
// 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();
|
|
}
|
|
}
|
|
|
|
|
|
//Adiciona essa tarefa a Ordem indicada em relação a execussão de tarefa.
|
|
$newOrderEquipmentTask = new OrderEquipmentTasks;
|
|
$newOrderEquipmentTask->equipmentWorkHistorys_id = $receiveEquipmentWorkHistory->equipmentWorkHistorys_id;
|
|
$newOrderEquipmentTask->execution_order = $insertPosition;
|
|
|
|
if ($request->selectedFurtherTaskExisting != 'null') {
|
|
// Se selectedFurtherTaskExisting não for 'null', então usa o ID da tarefa complementar selecionada
|
|
$newOrderEquipmentTask->elemental_tasks_id = $request->selectedFurtherTaskExisting;
|
|
} else {
|
|
// Caso contrário, usa o elemental_tasks_id do $newFurtherTask
|
|
$newOrderEquipmentTask->elemental_tasks_id = $newFurtherTask->elemental_tasks_id;
|
|
}
|
|
|
|
//Inspecionar Ainda não esta sendo utilizado.
|
|
$newOrderEquipmentTask->inspection = 2;
|
|
$newOrderEquipmentTask->save();
|
|
|
|
return redirect()->back()->with('success', 'Ordem de execução do equipamento: ' . $receiveDataEquipment->equipment_tag . ' Atulizada!');
|
|
}
|
|
|
|
public function receiveEquipmentToAssociateTasks(Request $request)
|
|
{
|
|
$receiveIsptNumber = 0;
|
|
|
|
// Obter o maior ispt_number da tabela EquipmentWorkHistory que corresponde aos valores em Equipment
|
|
$highestIsptNumber = EquipmentWorkHistory::select('equipment_work_historys.ispt_number')
|
|
->join('equipments', function ($join) {
|
|
$join->on('equipments.equipment_id', '=', 'equipment_work_historys.equipment_id')
|
|
->on('equipments.company_projects_id', '=', 'equipment_work_historys.company_projects_id');
|
|
})
|
|
->orderBy('equipment_work_historys.ispt_number', 'desc')
|
|
->first();
|
|
|
|
// Se existir, ele busca o maior número e acrescenta mais um para adicionar um novo equipamento.
|
|
if ($highestIsptNumber) {
|
|
$receiveIsptNumber = $highestIsptNumber->ispt_number + 1;
|
|
} else {
|
|
// Se não houver registros, comece com 1
|
|
$receiveIsptNumber = 1;
|
|
}
|
|
|
|
$execution_order = 1;
|
|
|
|
foreach ($request->equipment as $equipment) {
|
|
$equipmentModel = Equipment::where('equipment_id', $equipment['equipment_id'])->first();
|
|
|
|
//Atualiza a tabela equipment para associar o equipamento a uma Obra.
|
|
if ($equipmentModel) {
|
|
$equipmentModel->company_projects_id = $request->receiveNumberProject;
|
|
$equipmentModel->save();
|
|
|
|
// Utiliza firstOrCreate para evitar duplicidades
|
|
$attributes = [
|
|
'equipment_id' => $equipment['equipment_id'],
|
|
'company_projects_id' => $request->receiveNumberProject
|
|
];
|
|
|
|
$values = [
|
|
'ispt_number' => $receiveIsptNumber++ // Incrementa o número ISPT se criar um novo registro
|
|
];
|
|
|
|
$createEquipmentWorkHistory = EquipmentWorkHistory::firstOrCreate($attributes, $values);
|
|
|
|
//Criar associacao do equipamento ao Âmbito
|
|
$AssociationEquipmentAmbit = new EquipmentAssociationAmbit;
|
|
$AssociationEquipmentAmbit->equipment_type_id = $equipment['equipment_type_id'];
|
|
$AssociationEquipmentAmbit->ambits_id = $equipment['ambit_id'];
|
|
$AssociationEquipmentAmbit->equipmentWorkHistorys_id = $createEquipmentWorkHistory->id; // Note que mudamos para id
|
|
$AssociationEquipmentAmbit->save();
|
|
|
|
//Recebe a tabela com as associações entre Âmbitos e tarefas Elementares
|
|
$TasksAssociationAmbits = TasksAssociationAmbits::where('ambits_equipment_id', $AssociationEquipmentAmbit->ambits_id)->get();
|
|
|
|
foreach ($TasksAssociationAmbits as $TasksAssociationAmbit) {
|
|
$JoinsEquipmentsWithTasks = new OrderEquipmentTasks;
|
|
$JoinsEquipmentsWithTasks->equipmentWorkHistorys_id = $createEquipmentWorkHistory->id; // Note que mudamos para id
|
|
$JoinsEquipmentsWithTasks->execution_order = $execution_order++;
|
|
$JoinsEquipmentsWithTasks->elemental_tasks_id = $TasksAssociationAmbit->elemental_tasks_id;
|
|
// $JoinsEquipmentsWithTasks->further_tasks_id = null;
|
|
$JoinsEquipmentsWithTasks->inspection = 2;
|
|
$JoinsEquipmentsWithTasks->save();
|
|
}
|
|
}
|
|
}
|
|
|
|
return redirect()->back()->with('success', 'Equipametos associados a Obra com Sucesso !');
|
|
}
|
|
|
|
|
|
public function receiveUnitsForExcelTemplate($numberProject)
|
|
{
|
|
// Dados do Projecto
|
|
$receveCompanyProject = CompanyProject::where('company_projects_id', $numberProject)->first();
|
|
// Dados da Instalação
|
|
$recevePlant = Plant::where('plant_id', $receveCompanyProject->plant_id)->first();
|
|
// Dados das Fabricas
|
|
$receveUnits = Unit::where('plant_id', $recevePlant->plant_id)->get();
|
|
|
|
|
|
$filePath = public_path('templateExcel/Valves_Template.xlsx');
|
|
// Load the spreadsheet
|
|
$spreadsheet = IOFactory::load($filePath);
|
|
// Get the second sheet
|
|
$sheet = $spreadsheet->getSheet(1); // Sheet index starts from 0
|
|
|
|
// Define o valor de $numberProject na célula E2
|
|
$sheet->setCellValue('E2', $numberProject);
|
|
|
|
$row = 2; // Row number where you want to start inserting data
|
|
foreach ($receveUnits as $unit) {
|
|
// Set value for column D
|
|
$sheet->setCellValue('A' . $row, $unit->unit_name);
|
|
$row++;
|
|
}
|
|
|
|
$formattedDateTime = date('Y-m-d_H-i'); // Formato: Ano-Mês-Dia_Hora-Minuto
|
|
$fileName = "Valves_Template_{$numberProject}_{$formattedDateTime}.xlsx";
|
|
|
|
// Generate and return the download response
|
|
// return $this->createDownloadResponse($spreadsheet, 'Valves_Template.xlsx');
|
|
return $this->createDownloadResponse($spreadsheet, $fileName);
|
|
}
|
|
|
|
protected function createDownloadResponse($spreadsheet, $filename)
|
|
{
|
|
// Create a writer object
|
|
$writer = new Xlsx($spreadsheet);
|
|
// Create a StreamedResponse with a callback
|
|
$response = new StreamedResponse(
|
|
function () use ($writer) {
|
|
$writer->save('php://output');
|
|
}
|
|
);
|
|
// Set headers to indicate we're sending an Excel file
|
|
$response->headers->set('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
|
|
$response->headers->set('Content-Disposition', 'attachment;filename="' . $filename . '"');
|
|
$response->headers->set('Cache-Control', 'max-age=0');
|
|
|
|
return $response;
|
|
}
|
|
|
|
public function finishCreatingProject($numberProject)
|
|
{
|
|
// recebe atraves de sessao toda a vez quem entra no componente 'SelectElementalTasksInWonkstation' para selecionar as tarefas de cada Workstation
|
|
$receiveAllFurtherTasks = session('receiveAllFurtherTasks');
|
|
$receiveElementalTasks = session('receiveElementalTasks');
|
|
|
|
// Inicializar a matriz de IDs faltantes
|
|
$missingElementalTasks = [];
|
|
$missingFurtherTasksDetails = [];
|
|
$missingWorkstations = [];
|
|
|
|
$receiveDetailsProject = CompanyProject::where('company_projects_id', $numberProject)->first();
|
|
// dd($receiveDetailsProject);
|
|
|
|
// Recebe todos os dados dos postos de Trabalho
|
|
$receiveWorkstaions = ConstructionWorkstation::where('company_projects_id', $numberProject)->get();
|
|
|
|
// Verifica se a coleção está vazia
|
|
if ($receiveWorkstaions->isEmpty()) {
|
|
return redirect()->back()->with('danger', 'Nenhum posto foi criado ainda..');
|
|
}
|
|
|
|
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->elemental_tasks_id;
|
|
|
|
// Verificar se a tarefa está associada a algum id_workstations
|
|
$checkExistFurtherTaskInWs = WorkstationsAssociationTasks::whereIn('id_workstations', $workstationIds)
|
|
->where('elemental_tasks_id', $taskId)
|
|
->exists();
|
|
|
|
// Se não existe, adicionar à lista de tarefas faltantes
|
|
if (!$checkExistFurtherTaskInWs) {
|
|
$missingFurtherTasksDetails[$taskId] = [
|
|
'name' => $furtherTask->elemental_tasks_code,
|
|
'description' => $furtherTask->elemental_tasks_description
|
|
];
|
|
}
|
|
|
|
}
|
|
// dd($missingFurtherTasksDetails);
|
|
|
|
// 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 if ($receiveDetailsProject->order_project == 5) {
|
|
// Se for igual a 5 significa que forem adicionados apenas equipamentos extras e sendo assim precisa voltar para a Obra Em execução
|
|
$receiveDetailsProject->order_project = 3;
|
|
$receiveDetailsProject->save();
|
|
return redirect()->route('home');
|
|
|
|
} else {
|
|
$project = CompanyProject::find($numberProject);
|
|
$project->order_project = 2;
|
|
$project->save();
|
|
|
|
return redirect()->route('home');
|
|
}
|
|
}
|
|
|
|
public function deleteWorkstation($name)
|
|
{
|
|
$workstation = ConstructionWorkstation::where('name_workstations', $name)->first();
|
|
$removeAcountUserWorkstation = User::where('user_name', $workstation->name_workstations)->first();
|
|
|
|
if ($workstation && $removeAcountUserWorkstation) {
|
|
$workstation->delete();
|
|
$removeAcountUserWorkstation->delete();
|
|
|
|
// pegar o número da estação de trabalho que está sendo deletada
|
|
preg_match('/workstation(\d+)-/', $workstation->name_workstations, $matches);
|
|
$deletedWorkstationNumber = $matches[1];
|
|
|
|
// pega o número do projeto da estação de trabalho que está sendo deletada
|
|
$projectNumber = explode('-', $workstation->name_workstations)[1];
|
|
|
|
// pegar todas as estações de trabalho e Utilizadors com números maiores que o deletado e renumerá-los
|
|
$workstationsToUpdate = ConstructionWorkstation::where('company_projects_id', $projectNumber)
|
|
->whereRaw("SUBSTRING_INDEX(name_workstations, '-', 1) REGEXP '^workstation[0-9]+$'")
|
|
->whereRaw("CAST(SUBSTRING(SUBSTRING_INDEX(name_workstations, '-', 1), 12) AS UNSIGNED) >= ?", [$deletedWorkstationNumber])
|
|
->orderByRaw("CAST(SUBSTRING(SUBSTRING_INDEX(name_workstations, '-', 1), 12) AS UNSIGNED) DESC")
|
|
->get();
|
|
|
|
foreach ($workstationsToUpdate as $workstationToUpdate) {
|
|
// pegar o número da estação de trabalho atual
|
|
preg_match('/workstation(\d+)-/', $workstationToUpdate->name_workstations, $matches);
|
|
$currentWorkstationNumber = $matches[1];
|
|
|
|
// atualizar nome da estação de trabalho
|
|
$workstationToUpdate->name_workstations = 'workstation' . ($currentWorkstationNumber - 1) . '-' . $projectNumber;
|
|
$workstationToUpdate->save();
|
|
|
|
// atualizar Utilizador associado
|
|
$userToUpdate = User::where('user_name', 'workstation' . $currentWorkstationNumber . '-' . $projectNumber)->first();
|
|
if ($userToUpdate) {
|
|
$userToUpdate->user_name = 'workstation' . ($currentWorkstationNumber - 1) . '-' . $projectNumber;
|
|
$userToUpdate->save();
|
|
}
|
|
}
|
|
|
|
return back()->with('success', 'Posto de Trabalho removido com sucesso!');
|
|
}
|
|
return back()->with('danger', 'Posto de Trabalho não encontrado!');
|
|
}
|
|
|
|
public function removeProjectEquipment(Request $request)
|
|
{
|
|
|
|
$equipment = Equipment::find($request->EquipmentID);
|
|
|
|
if ($request->removalType == 'total') {
|
|
$equipment->delete();
|
|
|
|
return back()->with('success', 'Equipamento Excluido com sucesso!');
|
|
} else
|
|
$equipment->company_projects_id = null;
|
|
$equipment->save();
|
|
|
|
return back()->with('success', 'Equipamento retirado da obra !');
|
|
}
|
|
public function EditEquipment(Request $request)
|
|
{
|
|
|
|
// dd($request);
|
|
|
|
// Localiza o equipment pelo numberProject
|
|
$dataEquipment = Equipment::where('equipment_id', $request->equipmentID)->first();
|
|
|
|
// $receiveEquipmentWorkHistori = EquipmentWorkHistory::where('equipment_id', $request->equipmentID)
|
|
// ->where('company_projects_id', $dataEquipment->company_projects_id)
|
|
// ->first();
|
|
|
|
// Atualiza os campos
|
|
$dataEquipment->equipment_tag = $request->tag;
|
|
$dataEquipment->equipment_description = $request->equipmentDescription;
|
|
$dataEquipment->equipment_serial_number = $request->serialNumberEquipment;
|
|
$dataEquipment->equipment_brand = $request->equipmentBrand;
|
|
$dataEquipment->equipment_model = $request->equipmentModel;
|
|
|
|
$dataEquipment->save();
|
|
|
|
if ($request->input('attributes')) {
|
|
foreach ($request->input('attributes') as $key => $value) {
|
|
// Verifica se o valor é null e a chave é um número (correspondendo aos general_attributes_equipment_id)
|
|
if ($value == null && is_numeric($key)) {
|
|
// Procura o registro relevante em SpecificAttributesEquipmentType
|
|
$specificAttributes = SpecificAttributesEquipmentType::where('equipment_id', $dataEquipment->equipment_id)
|
|
->where('general_attributes_equipment_id', $key)
|
|
->first();
|
|
|
|
// Se o registro existir, o deleta
|
|
if ($specificAttributes) {
|
|
$specificAttributes->delete();
|
|
}
|
|
}
|
|
// Se o valor não for null, atualiza ou cria um novo registro
|
|
elseif ($value !== null && is_numeric($key)) {
|
|
|
|
// Procura o registro relevante em SpecificAttributesEquipmentType
|
|
$specificAttributes = SpecificAttributesEquipmentType::where('equipment_id', $dataEquipment->equipment_id)
|
|
->where('general_attributes_equipment_id', $key)
|
|
->first();
|
|
|
|
// Se o registro existir, atualiza o valor
|
|
if ($specificAttributes) {
|
|
$specificAttributes->specific_attributes_value = $value;
|
|
$specificAttributes->save();
|
|
}
|
|
// Se não existir, cria um novo
|
|
else {
|
|
// Cria um novo registro em SpecificAttributesEquipmentType
|
|
$specificAttributes = new SpecificAttributesEquipmentType();
|
|
$specificAttributes->equipment_id = $dataEquipment->equipment_id;
|
|
$specificAttributes->equipment_type_id = $dataEquipment->equipment_type_id;
|
|
$specificAttributes->general_attributes_equipment_id = $key;
|
|
$specificAttributes->specific_attributes_value = $value;
|
|
$specificAttributes->save();
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
return back()->with('success', 'Equipamento Atualizado!');
|
|
}
|
|
|
|
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->company_projects_id . '-' . $receiveNumberWorkstation . '@isptgroup.com';
|
|
$loginWorkStation->password = bcrypt($receveProjectCompanyNumber->company_projects_id . '-' . $receiveNumberWorkstation);
|
|
$loginWorkStation->type_users = 5;
|
|
$loginWorkStation->user_nif = $receveProjectCompanyNumber->company_projects_id . '-' . $receiveNumberWorkstation;
|
|
$loginWorkStation->save();
|
|
}
|
|
|
|
// Redireciona para onde você quiser após a criação das workstations
|
|
return redirect()->route('workStation_3', ['id' => $request->numberProject])
|
|
->with('success', $numberWorkstations . ' Postos de Trabalho criados !!!')
|
|
->with('listWorkstations', $listWorkstations);
|
|
}
|
|
|
|
// Funcao apenas para retornar os dados necessarios para a view criar uma Obra.
|
|
public function createProjectForStep1()
|
|
{
|
|
// $companies = User::where('type_users', 3)->get();
|
|
$companies = Company::all();
|
|
// 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);
|
|
|
|
$companies = Company::all();
|
|
|
|
$receiveDetailsPlant = Plant::where('plant_id', $projects->plant_id)->first();
|
|
|
|
$receiveDetailsCompany = Company::where('company_id', $receiveDetailsPlant->company_id)->first();
|
|
// $receiveDetailsUser = User::where('user_id', $receiveDetailsPlant->user_id)->first();
|
|
// $receiveDetailsUser->plantName = $receiveDetailsPlant->plant_name;
|
|
|
|
$projects->plantName = $receiveDetailsPlant->plant_name;
|
|
$projects->userName = $receiveDetailsCompany->company_name;
|
|
|
|
$receiveCompanyManager = '';
|
|
$receiveCompanyManagerID = null; // Inicialize com null ou um valor padrão apropriado
|
|
|
|
// Se o project_company_responsible for igual a null, significa que ainda não foi definido após a criação da Obra.
|
|
// Se foi definido, deve buscar o nome do User atribuído.
|
|
if ($projects->project_company_responsible === null) {
|
|
$receiveCompanyManager = 'Gestor da empresa ainda não atribuído...';
|
|
} else {
|
|
$NameCompanyManager = User::where('user_id', $projects->project_company_responsible)->first();
|
|
// Verifica se um usuário foi encontrado antes de tentar acessar a propriedade user_name.
|
|
if ($NameCompanyManager) {
|
|
$receiveCompanyManager = $NameCompanyManager->user_name;
|
|
$receiveCompanyManagerID = $NameCompanyManager->user_id;
|
|
} else {
|
|
$receiveCompanyManager = 'Usuário não encontrado'; // Mensagem caso o ID não corresponda a nenhum usuário.
|
|
$receiveCompanyManagerID = null; // Assegure-se que há um valor definido mesmo em caso de falha
|
|
}
|
|
}
|
|
$projects->NameCompanyManager = $receiveCompanyManager;
|
|
$projects->NameCompanyManagerID = $receiveCompanyManagerID;
|
|
|
|
|
|
//deve receber os User disponiveis da Empresa atual da Obra.
|
|
$receiveAllCompanyManager = AssociationCompanyUser::where('company_id', $projects->plant->company_id)->get();
|
|
|
|
return view('projectsClients/projectDetails_1', ['step' => 1], ['companies' => $companies])
|
|
->with('projects', $projects)
|
|
->with('receiveAllCompanyManager', $receiveAllCompanyManager);
|
|
}
|
|
|
|
// Se forem alterados dados dos Detalhes da Obra, vai ser alterado
|
|
public function EditprocessStep1(Request $request)
|
|
{
|
|
// Validação...
|
|
$project = CompanyProject::where('company_projects_id', $request->projectId)->first();
|
|
|
|
$project->company_project_description = $request->input('description_project');
|
|
$project->project_company_name = $request->input('project_company_name');
|
|
$project->project_ispt_number = $request->input('n_project_ispt');
|
|
$project->project_ispt_responsible = $request->input('responsible_project_ispt');
|
|
|
|
// Correção aqui: A verificação de 'undefined' deve ser feita corretamente
|
|
if ($request->input('responsible_project_company') === 'undefined') {
|
|
$project->project_company_responsible = null;
|
|
} else {
|
|
$project->project_company_responsible = $request->input('responsible_project_company');
|
|
}
|
|
|
|
// Verifica se existe uma nova data, se existe atualiza o projeto com a nova, se não existir usa a antiga
|
|
if ($request->input('date_started') !== null) {
|
|
$project->date_started = $request->input('date_started');
|
|
} else {
|
|
$project->date_started = $request->input('date_started_present');
|
|
}
|
|
|
|
$project->save();
|
|
|
|
session(['form_data.step1' => $request->all()]);
|
|
|
|
$receiveAllLogsProject = ProjectExcelLog::where('company_projects_id', $project->company_projects_id)
|
|
->get()
|
|
->groupBy('excel_name')
|
|
->map(function ($group) {
|
|
return $group->sortByDesc('project_excel_logs_id')->first();
|
|
});
|
|
|
|
return redirect()->route('articulated_2', ['projectID' => $project->company_projects_id])
|
|
->with('receiveAllLogsProject', $receiveAllLogsProject)
|
|
->with('success', 'Detalhes do Project atualizados!');
|
|
}
|
|
|
|
public function removePendingEquipment($id)
|
|
{
|
|
$equipment = PendingEquipment::findOrFail($id);
|
|
$equipment->delete();
|
|
return back()->with('success', 'Equipamento pendente removido com sucesso!');
|
|
}
|
|
|
|
public function CreateNewEquipmentFromPendingEquipment(Request $request, $id)
|
|
{
|
|
$checkPendingEquipment = PendingEquipment::findOrFail($id);
|
|
|
|
$counter = 2;
|
|
$baseTag = $checkPendingEquipment->pending_equipment_tag;
|
|
$baseDescription = $checkPendingEquipment->pending_equipment_description;
|
|
|
|
// Ciclo para verificar se já 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++;
|
|
}
|
|
|
|
$attributes = [
|
|
'unit_id' => $checkPendingEquipment->pending_equipment_unit_id,
|
|
'equipment_type_id' => $checkPendingEquipment->pending_equipment_type_id,
|
|
'equipment_tag' => $baseTag . "({$counter})",
|
|
'equipment_description' => $baseDescription . "({$counter})",
|
|
'company_projects_id' => $checkPendingEquipment->pending_company_projects_id
|
|
];
|
|
|
|
$newEquipment = Equipment::firstOrCreate($attributes);
|
|
|
|
$newEquipmentWorkHistoryAttributes = [
|
|
'equipment_id' => $newEquipment->equipment_id,
|
|
'company_projects_id' => $newEquipment->company_projects_id
|
|
];
|
|
|
|
$lastIsptNumber = EquipmentWorkHistory::where('company_projects_id', $newEquipment->company_projects_id)->max('ispt_number');
|
|
$newIsptNumber = $lastIsptNumber ? $lastIsptNumber + 1 : 1;
|
|
|
|
$valuesWorkHistory = [
|
|
'ispt_number' => $newIsptNumber,
|
|
'equipment_status_project' => 0
|
|
];
|
|
|
|
$newEquipmentWorkHistory = EquipmentWorkHistory::firstOrCreate($newEquipmentWorkHistoryAttributes, $valuesWorkHistory);
|
|
|
|
$newEquipmentAssociationAmbits = new EquipmentAssociationAmbit;
|
|
$newEquipmentAssociationAmbits->equipmentWorkHistorys_id = $newEquipmentWorkHistory->equipmentWorkHistorys_id;
|
|
$newEquipmentAssociationAmbits->ambits_id = $request->EquipmentAmbit;
|
|
$newEquipmentAssociationAmbits->equipment_type_id = $newEquipment->equipment_type_id;
|
|
$newEquipmentAssociationAmbits->save();
|
|
|
|
|
|
$TasksAssociationAmbits = TasksAssociationAmbits::where('ambits_equipment_id', $newEquipmentAssociationAmbits->ambits_id)->get();
|
|
|
|
foreach ($TasksAssociationAmbits as $TasksAssociationAmbit) {
|
|
$JoinsEquipmentsWithTasks = new OrderEquipmentTasks;
|
|
$JoinsEquipmentsWithTasks->equipmentWorkHistorys_id = $newEquipmentWorkHistory->equipmentWorkHistorys_id;
|
|
$JoinsEquipmentsWithTasks->elemental_tasks_id = $TasksAssociationAmbit->elemental_tasks_id;
|
|
$JoinsEquipmentsWithTasks->save();
|
|
}
|
|
|
|
$checkPendingEquipment->delete();
|
|
|
|
return back()->with('success', 'Equipamento ' . $newEquipment->equipment_tag . ' criado com sucesso');
|
|
}
|
|
|
|
|
|
|
|
public function processStep1(Request $request)
|
|
{
|
|
//NAO DEVE SER CRIAR UMA NOVA EMPRESA NA CRIACAO DA OBRA (era uma boa ideia para facilitar ao Admin ter que criar a empresa para Depois a Obra, mas e necessario pelo facto da autentificao de 2 factores e envio e email , entao devido essa adicoes, nao preciso atualmente fazer sentido criar isto)
|
|
// Dito isto vamos sempre pensar que o Cliente ja deve estar criado , para ser feita uma Obra para o mesmo.
|
|
// dd($request);
|
|
// Validação...
|
|
|
|
if ($request->input('installation_id')) {
|
|
|
|
$installationId = $request->input('installation_id');
|
|
|
|
//Para criar uma nova instalacao
|
|
if ($installationId <> null && $installationId == 'new_install') {
|
|
|
|
// Criar uma nova instalação...
|
|
$newInstallation = new Plant;
|
|
|
|
$newInstallation->plant_name = $request->input('new_company_name');
|
|
$newInstallation->plant_address = $request->input('new_company_address');
|
|
$newInstallation->company_id = $request->input('company_select');
|
|
|
|
$newInstallation->save();
|
|
|
|
// Use o id da nova instalação.
|
|
$installationId = $newInstallation->plant_id;
|
|
|
|
// Verifica se há nomes de fábricas para criar
|
|
$factoryNames = $request->input('factoryNames', []);
|
|
|
|
foreach ($factoryNames as $factoryName) {
|
|
$newUnit = new Unit; // Supondo que `Unit` é o seu modelo para as fábricas
|
|
$newUnit->unit_name = $factoryName;
|
|
$newUnit->plant_id = $installationId; // ID da instalação criada anteriormente
|
|
$newUnit->save(); // Salva a nova fábrica no banco de dados
|
|
}
|
|
|
|
}
|
|
}
|
|
|
|
$receiveDetailsPlant = Plant::where('plant_id', $installationId)->first();
|
|
|
|
//Code apenas para criacao de Obra sem criar instlacao ou empresa
|
|
$project = new CompanyProject;
|
|
$project->company_project_description = $request->input('description_project');
|
|
$project->project_ispt_number = $request->input('n_project_ispt');
|
|
$project->project_company_name = $request->input('project_company_name');
|
|
$project->project_ispt_responsible = $request->input('responsible_project_ispt');
|
|
|
|
if ($request->input('user_id') == 'ispt') {
|
|
$project->project_company_responsible = null;
|
|
} else {
|
|
$project->project_company_responsible = $request->input('user_id');
|
|
}
|
|
|
|
$project->plant_id = $receiveDetailsPlant->plant_id;
|
|
$project->order_project = 1;
|
|
$project->date_started = $request->input('date_started');
|
|
|
|
$project->save();
|
|
|
|
return redirect()->route('articulated_2', ['projectID' => $project->company_projects_id])
|
|
->with('success', 'Projeto Criado!');
|
|
}
|
|
|
|
public function showStep2($company_projects_id)
|
|
{
|
|
//A partida, nao precisa se uma session para guardar esses dados da pending, pois agora e guardado na DB
|
|
// $groupedArrayForPendingEquipments = session('groupedArrayForPendingEquipments');
|
|
// Verifique se a etapa 1 foi concluída
|
|
|
|
//recebe o Id de Plant vai devolver todos os equipamentos relacionados a esta Instalação(plant)
|
|
// Carregue o projeto com o id fornecido
|
|
$project = CompanyProject::find($company_projects_id);
|
|
|
|
$numberProject = $project->company_projects_id;
|
|
|
|
$typeEquipments = EquipmentType::all();
|
|
|
|
//Retorna todas as Fabricas Unit, com base na Instalação
|
|
$checkUnits = DB::table('units')
|
|
->join('plants', 'units.plant_id', '=', 'plants.plant_id')
|
|
->join('company_projects', 'plants.plant_id', '=', 'company_projects.plant_id')
|
|
->select('units.*')
|
|
->where('company_projects.company_projects_id', '=', $company_projects_id)
|
|
->get();
|
|
|
|
//Retorna todos os Equipamentos, com base na instalcao do projecto
|
|
$checkEquipments = DB::table('equipments')
|
|
->join('units', 'equipments.unit_id', '=', 'units.unit_id')
|
|
->join('plants', 'units.plant_id', '=', 'plants.plant_id')
|
|
->select('equipments.*') // Seleciona todas as colunas da tabela 'equipments'
|
|
->where('plants.plant_id', '=', $project['plant_id']) // Filtra baseado no 'plant_id'
|
|
->get();
|
|
|
|
// Para listar os equipamentos vinculados na obra, buscamos suas associações gerais entre suas tabelas , ou seja a : fabrica(unit), tipo de equipamento e o Âmbito para se realizar a tarefas pretendida neste obra.
|
|
// $listEquipmentsProjects = Equipment::with(['unit', 'equipmentType', 'equipmentAssociationAmbit.ambitsEquipment'])
|
|
// ->where('company_projects_id', $company_projects_id)
|
|
// ->get();
|
|
|
|
$listEquipmentsProjects = Equipment::with([
|
|
'unit',
|
|
'equipmentType',
|
|
// 'equipmentAssociationAmbit.ambitsEquipment',
|
|
'specificAttributes' => function ($query) {
|
|
$query->orderBy('specific_attributes_value', 'asc');
|
|
}
|
|
])
|
|
->where('company_projects_id', $company_projects_id)
|
|
->get();
|
|
|
|
$pendingEquipments = PendingEquipment::where('pending_company_projects_id', $numberProject)->get();
|
|
|
|
// $receiveAllLogsProject = ProjectExcelLog::where('company_projects_id', $company_projects_id)->get();
|
|
|
|
$receiveAllLogsProject = ProjectExcelLog::where('company_projects_id', $company_projects_id)
|
|
->get()
|
|
->groupBy('excel_name')
|
|
->map(function ($group) {
|
|
return $group->sortByDesc('project_excel_logs_id')->first();
|
|
});
|
|
|
|
|
|
if (!$pendingEquipments->isEmpty()) {
|
|
// Retornamos para a view 'step' => 2 indicando conclusao da primeira parte, $numberProject para associacao de equipamentos a esta obra, alem de todos os equipamentos e fabricao ja existente com base na Instalação que se iniciou a obra.
|
|
return view('projectsClients/articulated_2', ['step' => 2, 'numberProject' => $numberProject])
|
|
->with('danger', 'Equipamentos Pendentes: ' . count($pendingEquipments))
|
|
->with('pendingEquipments', $pendingEquipments)
|
|
->with('listEquipmentsProjects', $listEquipmentsProjects)
|
|
->with('typeEquipments', $typeEquipments)
|
|
->with('checkEquipments', $checkEquipments)
|
|
->with('checkUnits', $checkUnits)
|
|
->with('receiveNumberProject', $project)
|
|
// ->with('groupedArrayForPendingEquipments', $groupedArrayForPendingEquipments)
|
|
->with('receiveAllLogsProject', $receiveAllLogsProject);
|
|
}
|
|
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)
|
|
->with('receiveAllLogsProject', $receiveAllLogsProject);
|
|
}
|
|
|
|
public function createEquipmentManual(Request $request)
|
|
{
|
|
$detailsCompanyProject = CompanyProject::where('company_projects_id', $request->numberProject)->first();
|
|
|
|
// EquipmentAmbit
|
|
// *** Recebe a Instalação(Plant), com base no número da Obra Criada
|
|
$receivePlant = DB::table('plants')
|
|
->join('company_projects', 'company_projects.plant_id', 'plants.plant_id')
|
|
->select('plants.plant_id')
|
|
->where('company_projects.company_projects_id', '=', $request->numberProject)
|
|
->get();
|
|
|
|
//recebe a lista de todos os equipmentos relacionados a obra que se esta a criar.
|
|
$listEquipmentsProjects = DB::table('equipments')
|
|
->select('equipments.*')
|
|
->where('equipments.company_projects_id', '=', $request->numberProject)
|
|
->get();
|
|
|
|
// Verifica se ja existe um equipamento com as as caracteristicas : tag,unit_id, iguais ao que pretendemos criar
|
|
$existingEquipment = Equipment::firstWhere([
|
|
'equipment_tag' => $request->tag,
|
|
'unit_id' => $request->unit_id
|
|
]);
|
|
|
|
if ($existingEquipment) {
|
|
return redirect()->route('articulated_2', ['projectID' => $request->numberProject])
|
|
->with('danger', 'Equipamento ja Existe !!')
|
|
->with('listEquipmentsProjects', $listEquipmentsProjects);
|
|
}
|
|
|
|
// Se realmente for um equipamento novo, verifica se ira associar a uma fabrica (unit) nova ou ja existente
|
|
$newEquipmentProject = new Equipment;
|
|
|
|
// Se for uma fabrica(Unit) existente
|
|
if ($request->new_unit_name == null) {
|
|
$newEquipmentProject->unit_id = $request->unit_id;
|
|
} else {
|
|
|
|
//ja retorna se for uma fabrica nova (Unit)
|
|
$newUnit = new Unit;
|
|
$newUnit->unit_name = $request->new_unit_name;
|
|
$newUnit->plant_id = $receivePlant[0]->plant_id;
|
|
$newUnit->save();
|
|
|
|
$newEquipmentProject->unit_id = $newUnit->unit_id;
|
|
}
|
|
|
|
$newEquipmentProject->equipment_type_id = $request->equipmentTypeId;
|
|
$newEquipmentProject->equipment_tag = $request->tag;
|
|
$newEquipmentProject->equipment_description = $request->equipmentDescription;
|
|
|
|
// Estes campos a baixo : podem ter valor ou não
|
|
$newEquipmentProject->equipment_serial_number = $request->serialNumberEquipment ?? NULL;
|
|
$newEquipmentProject->equipment_brand = $request->equipmentBrand ?? NULL;
|
|
$newEquipmentProject->equipment_model = $request->equipmentModel ?? NULL;
|
|
|
|
$newEquipmentProject->company_projects_id = $request->numberProject;
|
|
|
|
$newEquipmentProject->save();
|
|
|
|
// ID do equipamento criado
|
|
$equipmentID = $newEquipmentProject->equipment_id;
|
|
|
|
$newEquipmentWorkHistorys = new EquipmentWorkHistory;
|
|
|
|
// Verifica se já existem registros com o mesmo 'equipment_id' e 'company_projects_id'
|
|
$existingRecords = EquipmentWorkHistory::where('company_projects_id', $request->numberProject)
|
|
->orderBy('ispt_number', 'desc') // Ordena de forma decrescente
|
|
->first(); // Pega o primeiro resultado, que seria o maior número
|
|
|
|
if ($existingRecords) {
|
|
// Se existirem registros, o próximo número será o maior número existente + 1
|
|
$isptNumber = $existingRecords->ispt_number + 1;
|
|
} else {
|
|
// Se não existirem registros, começa com 1
|
|
$isptNumber = 1;
|
|
}
|
|
|
|
$newEquipmentWorkHistorys->equipment_status_project = 0;
|
|
$newEquipmentWorkHistorys->equipment_id = $equipmentID;
|
|
$newEquipmentWorkHistorys->ispt_number = $isptNumber;
|
|
$newEquipmentWorkHistorys->company_projects_id = $request->numberProject;
|
|
|
|
|
|
if ($detailsCompanyProject->order_project == 5) {
|
|
$newEquipmentWorkHistorys->extra_equipment = 1;
|
|
} else {
|
|
$newEquipmentWorkHistorys->extra_equipment = 0;
|
|
}
|
|
$newEquipmentWorkHistorys->save();
|
|
|
|
|
|
$equipmentWorkHistorysID = $newEquipmentWorkHistorys->equipmentWorkHistorys_id;
|
|
|
|
// Verifica os campos do Card_do tipo de valvula selecionado (Ex: psv_card) e de acordo com os campos preenchidos se for de atributos especificos, ele compara o 'name' dos inputs com os 'general_attributes_equipment_description' da tabela : GeneralAttributesEquipment e associa
|
|
$checkAtributs = GeneralAttributesEquipment::whereIn('general_attributes_equipment_description', array_keys($request->all()))
|
|
->pluck('general_attributes_equipment_id', 'general_attributes_equipment_description')
|
|
->toArray();
|
|
|
|
// Recebe esta associacao, e cria um array para cada 'name'(inputs) igual ao 'general_attributes_equipment_description', contanto que seu valor(input) seja diferente de *NULL, assim o "$receivesAssociationAttributes" recebe o id de acordo com a tabela , o nome de acordo com a tabela e o valor do $request recebido associado ao campo
|
|
$receivesAssociationAttributes = [];
|
|
foreach ($checkAtributs as $description => $id) {
|
|
if ($request[$description] !== null) {
|
|
$receivesAssociationAttributes[] = [
|
|
'general_attributes_equipment_id' => $id,
|
|
'general_attributes_equipment_description' => $description,
|
|
'value' => $request[$description]
|
|
];
|
|
}
|
|
}
|
|
// Para cada um dos Arrays criados acima, vai criar os novos dados na tabela 'SpecificAttributesEquipmentType'
|
|
foreach ($receivesAssociationAttributes as $receivesAssociationAttribute) {
|
|
|
|
$AddAtributsEquipments = new SpecificAttributesEquipmentType;
|
|
$AddAtributsEquipments->equipment_id = $equipmentID;
|
|
$AddAtributsEquipments->equipment_type_id = $request->equipmentTypeId;
|
|
$AddAtributsEquipments->general_attributes_equipment_id = $receivesAssociationAttribute['general_attributes_equipment_id'];
|
|
$AddAtributsEquipments->specific_attributes_value = $receivesAssociationAttribute['value'];
|
|
|
|
$AddAtributsEquipments->save();
|
|
}
|
|
//Criar associacao do equipamento ao Âmbito
|
|
$AssociationEquipmentAmbit = new EquipmentAssociationAmbit;
|
|
$AssociationEquipmentAmbit->equipment_type_id = $request->equipmentTypeId;
|
|
$AssociationEquipmentAmbit->ambits_id = $request->EquipmentAmbit;
|
|
$AssociationEquipmentAmbit->equipmentWorkHistorys_id = $equipmentWorkHistorysID;
|
|
|
|
$AssociationEquipmentAmbit->save();
|
|
|
|
$execution_order = 1;
|
|
|
|
//Recebe a tabela com as associoacoes entre Âmbitos e tarefas Elementares
|
|
$TasksAssociationAmbits = TasksAssociationAmbits::all()->where('ambits_equipment_id', $AssociationEquipmentAmbit->ambits_id);
|
|
|
|
foreach ($TasksAssociationAmbits as $TasksAssociationAmbit) {
|
|
$JoinsEquipmentsWithTasks = new OrderEquipmentTasks;
|
|
$JoinsEquipmentsWithTasks->equipmentWorkHistorys_id = $equipmentWorkHistorysID;
|
|
$JoinsEquipmentsWithTasks->execution_order = $execution_order++;
|
|
$JoinsEquipmentsWithTasks->elemental_tasks_id = $TasksAssociationAmbit->elemental_tasks_id;
|
|
// $JoinsEquipmentsWithTasks->further_tasks_id = null;
|
|
$JoinsEquipmentsWithTasks->inspection = 2;
|
|
$JoinsEquipmentsWithTasks->save();
|
|
}
|
|
|
|
// O $request->numberProject e sempre necessario retornar para indicar a obra que se esta modificando...
|
|
return redirect()->route('articulated_2', ['projectID' => $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;
|
|
// Recebe mais detalhes da Obra Atual.
|
|
$detailsCompanyProject = CompanyProject::where('company_projects_id', $company_projects_id)->first();
|
|
// Inicializa o contador para ispt_number
|
|
$isptNumber = 1;
|
|
|
|
// Confirma que o arquivo foi enviado,ou seja sua existencia.
|
|
// Antes de verificar o documento excel, deve ter uma forma de confirmar o mesmo como arquivo legitivo para criar dados de acordo com o nosso template.
|
|
if ($file) {
|
|
|
|
//Busca o nome do arquivo xslx.
|
|
$originalFileName = $file->getClientOriginalName();
|
|
// Carregue o arquivo Excel
|
|
$spreadsheet = IOFactory::load($file->path());
|
|
|
|
// Verifica se existe uma sheet chamada 'list'
|
|
if ($spreadsheet->sheetNameExists('lists')) {
|
|
$listSheet = $spreadsheet->getSheetByName('lists');
|
|
|
|
// Verifica o valor da célula E2 na sheet 'list'
|
|
$sheetValueE2 = $listSheet->getCell('E2')->getValue();
|
|
|
|
// Compara com o valor de $request->numberProject
|
|
if ($sheetValueE2 != $request->numberProject) {
|
|
|
|
// Decide a rota de redirecionamento com base em 'order_project' se osnumeros da Obra nao forem o mesmo
|
|
if ($detailsCompanyProject->order_project == 5) {
|
|
return redirect()->route('changeFromExecutionToPlanning', ['projectID' => $request->numberProject])
|
|
->with('danger', 'Arquivo ignorado, Template de outra Obra');
|
|
} else {
|
|
return redirect()->route('articulated_2', ['projectID' => $request->numberProject])
|
|
->with('danger', 'Arquivo ignorado, Template de outra Obra');
|
|
}
|
|
}
|
|
} else {
|
|
// Decide a rota de redirecionamento se a sheet 'lists' não existir
|
|
if ($detailsCompanyProject->order_project == 5) {
|
|
return redirect()->route('changeFromExecutionToPlanning', ['projectID' => $request->numberProject])
|
|
->with('danger', 'Arquivo ignorado, por não ser compatível com a template 4.0');
|
|
} else {
|
|
return redirect()->route('articulated_2', ['projectID' => $request->numberProject])
|
|
->with('danger', 'Arquivo ignorado, por não ser compatível com a template 4.0');
|
|
}
|
|
}
|
|
|
|
|
|
// Obtenha a primeira planilha, onde fica os nomes chaves para associar as tabelas : 'general_attributes_equipaments' ,'equipments' e 'equipmentWorkHistorys'
|
|
$worksheet = $spreadsheet->getSheet(0);
|
|
// Transforme os dados da planilha em um array
|
|
$data = $worksheet->toArray();
|
|
|
|
// Retorna um array com todos os names preenchidos na primeira linha do template de Excel
|
|
$columnNames = $data[0];
|
|
$countPendingEquipments = 0;
|
|
$countEquipment = 0;
|
|
|
|
// Recebo os nomes das colunas do execel dependendo da linguagem selecionada
|
|
$columnRealNames = $data[5];
|
|
|
|
// Inicialização do hashmap para rastrear as linhas únicas
|
|
$uniqueRowsHashmap = [];
|
|
$equipmentPendingLogs = [];
|
|
// $ignoredLines = [];
|
|
// $duplicateLines = [];
|
|
|
|
// 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
|
|
|
|
//Funcao para padronizar as respostas, como eliminar espacos em branco e reduzir o texto sempre para minisculas
|
|
function normalize($value)
|
|
{
|
|
// Remove espaços em branco no início e no fim da string
|
|
$trimmed = trim($value);
|
|
// Remove espaços em branco no meio da string
|
|
$noInnerSpaces = str_replace(' ', '', $trimmed);
|
|
// Converte a string para minúsculas
|
|
$lowercase = strtolower($noInnerSpaces);
|
|
return $lowercase;
|
|
}
|
|
|
|
// Busca o ID de todas as unidades referentes à Instalação da Obra e coloca em um array
|
|
$allUnitsOnThePlantOfProject = Unit::where('plant_id', $detailsCompanyProject->plant_id)
|
|
->pluck('unit_id')
|
|
->toArray();
|
|
|
|
// Busca os equipamentos com base nos IDs das unidades encontradas
|
|
$equipments = Equipment::select('equipment_id', 'unit_id', 'equipment_tag') // Substitua 'equipment_id', 'equipment_tag' pelos nomes corretos das colunas, se necessário
|
|
->whereIn('unit_id', $allUnitsOnThePlantOfProject)
|
|
->get()->keyBy(function ($item) {
|
|
return normalize($item->unit->unit_name) . '-' . normalize($item->equipment_tag); // Cria uma chave única com 'unit_id-tag' para fácil comparação
|
|
});
|
|
|
|
// Verifica se já existem registros com o mesmo 'equipment_id' e 'company_projects_id'
|
|
$existingRecords = EquipmentWorkHistory::where('company_projects_id', $company_projects_id)
|
|
->orderBy('ispt_number', 'desc') // Ordena de forma decrescente
|
|
->first(); // Pega o primeiro resultado, que seria o maior número
|
|
|
|
if ($existingRecords) {
|
|
// Se existirem registros, o próximo número será o maior número existente + 1
|
|
$isptNumber = $existingRecords->ispt_number + 1;
|
|
} else {
|
|
// Se não existirem registros, começa com 1
|
|
$isptNumber = 1;
|
|
}
|
|
|
|
foreach ($data as $i => $dataLines) {
|
|
|
|
// Em cada um das linhas horizontais do excel, vai se guardar a 'key' vinculada ao valor do campo preenchido ou seja a 'key' vai ter o mesmo nome de um dos dados da tabela 'general_attributes_equipaments' na coluna : general_attributes_equipment_description, assim sendo mais facil implementar na tabela : specific_attributes_equipament_types
|
|
$joinArrays = array_combine($columnNames, $dataLines);
|
|
|
|
// vai guardar todos os campos de possiveis novos equipamentos, cada um em um array para multiplos inserts, na base de dados
|
|
$datas = array_filter($joinArrays, function ($chave) {
|
|
return !empty($chave);
|
|
}, ARRAY_FILTER_USE_KEY);
|
|
|
|
// 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;
|
|
}
|
|
|
|
// Recebe os detalhes da Unit recebida nesta linha do excel.
|
|
// Deve verificar a Plant tambem, pois pode ter outra plante com esse mesmo nome de fabrica.
|
|
//Nunca vai ser null ou diferente pois tem um code acima que se essa coluna for null faz um continue na linha atual XD
|
|
$detailsUnit = Unit::where('unit_name', $datas['unit'])
|
|
->where('plant_id', $detailsCompanyProject->plant_id)
|
|
->first();
|
|
|
|
|
|
//Indentifica qual o tipo de equipamento selecionado de acordo com a tabela EquipmentType
|
|
$equipmentType = EquipmentType::where('equipment_type_name', $datas['equipment_type_name'])->first();
|
|
|
|
//-------- Linhas Ignoradas
|
|
// Começa a contagem das linhas do excel a partir de 7 linha
|
|
if ($i < 6) {
|
|
continue;
|
|
}
|
|
// Contador para campos não vazios
|
|
$nonEmptyFieldsCount = 0;
|
|
// Array para rastrear campos não preenchidos
|
|
$missingFields = [];
|
|
|
|
// Verifica se os 5 primeiros campos estão preenchidos e conta os não vazios
|
|
for ($j = 0; $j < 5; $j++) {
|
|
if (!empty($dataLines[$j])) {
|
|
$nonEmptyFieldsCount++;
|
|
} else {
|
|
$missingFields[] = $columnRealNames[$j]; // Assume-se que $columnRealNames mapeia corretamente para os nomes dos campos
|
|
}
|
|
}
|
|
|
|
// Registra a linha como ignorada se menos de 2 campos estiverem preenchidos ou se houver campos não preenchidos
|
|
if ($nonEmptyFieldsCount > 2 && $nonEmptyFieldsCount < 5) {
|
|
$equipmentPendingLogs[] = [
|
|
'typePendingLog' => 0,
|
|
'line' => $i + 1,
|
|
'reason' => implode(', ', $missingFields), // Converte o array de campos faltantes para uma string
|
|
];
|
|
continue; // Pula para a próxima linha
|
|
}
|
|
|
|
|
|
//-------- Linhas Repetidas no Execel
|
|
$normalizedField1 = normalize($dataLines[0]);
|
|
$normalizedField2 = normalize($dataLines[1]);
|
|
$key = $normalizedField1 . '-' . $normalizedField2;
|
|
|
|
// Verifica duplicatas no Excel
|
|
if (!array_key_exists($key, $uniqueRowsHashmap)) {
|
|
$uniqueRowsHashmap[$key] = $i;
|
|
} else {
|
|
$duplicateLines[] = $i; // Linha duplicada no Excel
|
|
|
|
//Guardar os informacoes para o logs geral da pagina de articulado
|
|
$equipmentPendingLogs[] = [
|
|
'excel_Name' => $originalFileName,
|
|
'typePendingLog' => 1,
|
|
'duplicate_line' => $i + 1,
|
|
'original_line' => $uniqueRowsHashmap[$key] + 1,
|
|
'reason' => 'Duplicata no Excel - (Original Line ' . $uniqueRowsHashmap[$key] + 1 . ') referente aos campos: ' . $columnRealNames[0] . ' e ' . $columnRealNames[1] . '.'
|
|
];
|
|
|
|
//este e criado apenas para o PendingEquipment a indicar a reason de sua criacao.
|
|
$pending_equipment_creation_log = [
|
|
'excel_Name' => $originalFileName,
|
|
'reason' => 'Duplicata no Excel - (Original Line ' . $uniqueRowsHashmap[$key] + 1 . ') referente aos campos: ' . $columnRealNames[0] . ' e ' . $columnRealNames[1] . '.(Duplicate Line ' . $i + 1 . ')'
|
|
];
|
|
|
|
$pendingEquipament = new PendingEquipment;
|
|
|
|
// Defina os atributos do pendingEquipament conforme necessário.
|
|
$pendingEquipament->pending_equipment_unit_id = $detailsUnit->unit_id;
|
|
$pendingEquipament->pending_equipment_type_id = $equipmentType->equipment_type_id;
|
|
$pendingEquipament->pending_equipment_tag = $datas['equipment_tag'];
|
|
$pendingEquipament->pending_equipment_description = $datas['equipment_description'];
|
|
|
|
//recebe os valores de $equipmentPendingLogs para guardar o logs de criacao deste pendente.
|
|
$pendingEquipament->pending_equipment_creation_log = json_encode($pending_equipment_creation_log);
|
|
|
|
$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++;
|
|
|
|
continue; // Pula a próxima verificação para duplicatas identificadas no Excel
|
|
}
|
|
|
|
//--------- Linhas associada a equipamentos da base de dados.
|
|
// Verifica duplicatas na base de dados
|
|
if (isset($equipments[$key])) {
|
|
$duplicateLines[] = $i; // Linha duplicada na base de dados
|
|
$equipmentPendingLogs[] = [
|
|
'typePendingLog' => 2,
|
|
'line' => $i + 1,
|
|
'equipment_id' => $equipments[$key]->equipment_id, // Adiciona o ID do equipamento
|
|
'equipment_tag' => $equipments[$key]->equipment_tag, // Adiciona a tag do equipamento
|
|
'reason' => '' // Adiciona uma razão vazia por padrão que será atualizada mais tarde
|
|
];
|
|
|
|
// Busca o equipamento para ver se já está associado a algum projeto
|
|
$findEquipment = Equipment::find($equipments[$key]->equipment_id);
|
|
|
|
if ($findEquipment->company_projects_id != null && $findEquipment->company_projects_id == $company_projects_id) {
|
|
$equipmentPendingLogs[count($equipmentPendingLogs) - 1]['reason'] = 'Equipamento já associado a esta obra';
|
|
$equipmentPendingLogs[count($equipmentPendingLogs) - 1]['typePendingLog'] = 2.1;
|
|
|
|
} elseif ($findEquipment->company_projects_id != null && $findEquipment->company_projects_id != $company_projects_id) {
|
|
$findOtherCompanyProject = CompanyProject::find($findEquipment->company_projects_id);
|
|
$equipmentPendingLogs[count($equipmentPendingLogs) - 1]['reason'] = 'Equipamento associado a outra Obra: ' . $findOtherCompanyProject->company_project_description;
|
|
$equipmentPendingLogs[count($equipmentPendingLogs) - 1]['typePendingLog'] = 2.2;
|
|
|
|
} else {
|
|
//equipamentos novos nao entram na equipmentPendingLogs, criar um proprio apenas para teste.
|
|
$equipmentPendingLogs[count($equipmentPendingLogs) - 1]['reason'] = 'Equipamento associado a obra com sucesso!';
|
|
$equipmentPendingLogs[count($equipmentPendingLogs) - 1]['typePendingLog'] = 2.3;
|
|
|
|
// Associar o equipamento à Obra atual
|
|
$findEquipment->company_projects_id = $company_projects_id;
|
|
$findEquipment->save();
|
|
|
|
//Apenas para indicar qtd de equipamentos criados
|
|
$countEquipment++;
|
|
|
|
// Criar um equipment_work_historys
|
|
$newEquipmentWorkHistory = new EquipmentWorkHistory;
|
|
$newEquipmentWorkHistory->equipment_id = $findEquipment->equipment_id;
|
|
$newEquipmentWorkHistory->equipment_status_project = 0;
|
|
$newEquipmentWorkHistory->ispt_number = $isptNumber++;
|
|
$newEquipmentWorkHistory->company_projects_id = $company_projects_id;
|
|
|
|
//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 {
|
|
$newEquipmentWorkHistory->extra_equipment = 0;
|
|
}
|
|
$newEquipmentWorkHistory->save();
|
|
|
|
|
|
//Adicionar Ambito e Tarefas para fazer.
|
|
$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 = $findEquipment->equipment_type_id;
|
|
$AssociationEquipmentAmbit->ambits_id = $ambit_id;
|
|
$AssociationEquipmentAmbit->equipmentWorkHistorys_id = $newEquipmentWorkHistory->equipmentWorkHistorys_id;
|
|
|
|
$AssociationEquipmentAmbit->save();
|
|
|
|
|
|
// Criar um registro em HistoryOfEquipmentAmbitsInTheProject
|
|
$newHistoryOfEquipmentAmbits = new HistoryOfEquipmentAmbitsInTheProject;
|
|
$newHistoryOfEquipmentAmbits->equipmentWorkHistorys_id = $newEquipmentWorkHistory->equipmentWorkHistorys_id;
|
|
$newHistoryOfEquipmentAmbits->ambits_id = $ambit->ambits_id;
|
|
$newHistoryOfEquipmentAmbits->save();
|
|
|
|
//Recebe a tabela com as associoacoes entre Âmbitos e tarefas Elementares
|
|
$TasksAssociationAmbits = TasksAssociationAmbits::all()->where('ambits_equipment_id', $AssociationEquipmentAmbit->ambits_id);
|
|
$execution_order = 1;
|
|
|
|
foreach ($TasksAssociationAmbits as $TasksAssociationAmbit) {
|
|
$JoinsEquipmentsWithTasks = new OrderEquipmentTasks;
|
|
$newEquipmentWorkHistory->ispt_number = $isptNumber++;
|
|
$JoinsEquipmentsWithTasks->equipmentWorkHistorys_id = $newEquipmentWorkHistory->equipmentWorkHistorys_id;
|
|
$JoinsEquipmentsWithTasks->elemental_tasks_id = $TasksAssociationAmbit->elemental_tasks_id;
|
|
$JoinsEquipmentsWithTasks->save();
|
|
}
|
|
|
|
}
|
|
|
|
|
|
continue; // Pula para a próxima iteração
|
|
|
|
//----- Para equipamento novos, nao pendentes. ---------
|
|
// Caso a linha nao se enquadre em nenhuma das verificacoes anteriores, ele sera considerado um equipamento novo.
|
|
} else {
|
|
|
|
//--------- Novo equipamento
|
|
$newEquipament = new Equipment;
|
|
$newEquipament->unit_id = $detailsUnit->unit_id;
|
|
$newEquipament->equipment_type_id = $equipmentType->equipment_type_id;
|
|
$newEquipament->equipment_Description = $datas['equipment_description'];
|
|
$newEquipament->equipment_tag = $datas['equipment_tag'];
|
|
$newEquipament->equipment_serial_number = $datas['serial_number'];
|
|
$newEquipament->equipment_brand = $datas['brand'];
|
|
$newEquipament->equipment_model = $datas['model'];
|
|
$newEquipament->company_projects_id = $company_projects_id;
|
|
|
|
$newEquipament->save();
|
|
|
|
|
|
$countEquipment++;
|
|
|
|
//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;
|
|
$newEquipmentWorkHistory->equipment_id = $newEquipament->equipment_id;
|
|
$newEquipmentWorkHistory->ispt_number = $isptNumber++;
|
|
$newEquipmentWorkHistory->company_projects_id = $company_projects_id;
|
|
$newEquipmentWorkHistory->equipment_status_project = 0;
|
|
|
|
if ($detailsCompanyProject->order_project == 5) {
|
|
$newEquipmentWorkHistory->extra_equipment = 1;
|
|
} else {
|
|
$newEquipmentWorkHistory->extra_equipment = 0;
|
|
}
|
|
|
|
$newEquipmentWorkHistory->save();
|
|
|
|
$ambit = AmbitsEquipment::where('ambits_description', $datas['ambit'])->first();
|
|
|
|
if ($ambit) {
|
|
$ambit_id = $ambit->ambits_id;
|
|
}
|
|
|
|
//Criar associacao do equipamento ao Âmbito
|
|
$AssociationEquipmentAmbit = new EquipmentAssociationAmbit;
|
|
$AssociationEquipmentAmbit->equipment_type_id = $newEquipament->equipment_type_id;
|
|
$AssociationEquipmentAmbit->ambits_id = $ambit_id;
|
|
$AssociationEquipmentAmbit->equipmentWorkHistorys_id = $newEquipmentWorkHistory->equipmentWorkHistorys_id;
|
|
|
|
$AssociationEquipmentAmbit->save();
|
|
|
|
// Criar um registro em HistoryOfEquipmentAmbitsInTheProject
|
|
$newHistoryOfEquipmentAmbits = new HistoryOfEquipmentAmbitsInTheProject;
|
|
$newHistoryOfEquipmentAmbits->equipmentWorkHistorys_id = $newEquipmentWorkHistory->equipmentWorkHistorys_id;
|
|
$newHistoryOfEquipmentAmbits->ambits_id = $ambit->ambits_id;
|
|
$newHistoryOfEquipmentAmbits->save();
|
|
|
|
//Recebe a tabela com as associoacoes entre Âmbitos e tarefas Elementares
|
|
$TasksAssociationAmbits = TasksAssociationAmbits::all()->where('ambits_equipment_id', $AssociationEquipmentAmbit->ambits_id);
|
|
$execution_order = 1;
|
|
|
|
foreach ($TasksAssociationAmbits as $TasksAssociationAmbit) {
|
|
$JoinsEquipmentsWithTasks = new OrderEquipmentTasks;
|
|
$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
|
|
session(['groupedArrayForPendingEquipments' => $groupedArrayForPendingEquipments]);
|
|
|
|
$equipmentPendingLogs[] = [
|
|
'typePendingLog' => 3,
|
|
'line' => $i + 1,
|
|
'reason' => 'Equipamento Novo' // Adiciona uma razão vazia por padrão que será atualizada mais tarde
|
|
];
|
|
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.
|
|
|
|
}
|
|
|
|
$countEquipment; //Qtd de equipamentos novos criados
|
|
$countPendingEquipments; // Qtd de equipamentos pendentes criados
|
|
|
|
|
|
$createProjectLogs = new ProjectExcelLog;
|
|
$createProjectLogs->company_projects_id = $detailsCompanyProject->company_projects_id;
|
|
$createProjectLogs->excel_name = $originalFileName;
|
|
$createProjectLogs->excel_logs = $equipmentPendingLogs;
|
|
|
|
$createProjectLogs->save();
|
|
|
|
// Distiguir entre Articulado 'Normal' e 'Extra'
|
|
if ($detailsCompanyProject->order_project == 5) {
|
|
return redirect()->route('changeFromExecutionToPlanning', ['projectID' => $request->numberProject])
|
|
->with('success', 'Equipamentos Extras adicionados!');
|
|
}
|
|
|
|
return redirect()->route('articulated_2', ['projectID' => $request->numberProject])
|
|
->with('success', 'Equipamentos criados com sucesso !');
|
|
//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');
|
|
// Nenhum arquivo enviado para verificacao do excel.
|
|
} else {
|
|
return redirect()->route('articulated_2', ['projectID' => $request->numberProject])
|
|
->with('danger', 'Arquivo ignorado , por nao ser compativel com a template 4.0');
|
|
// Nenhum arquivo enviado para verificacao do excel.
|
|
}
|
|
|
|
// //Nao chega aqui ainda pois volta para a pagina com dados ja carregados.
|
|
// session(['form_data.step2' => $request->all()]);
|
|
|
|
// // Redirecione o Utilizador para a próxima etapa
|
|
// return redirect('/workStation_3');
|
|
}
|
|
|
|
public function showStep3($company_projects_id)
|
|
{
|
|
|
|
$receiveDataCompanyProject= CompanyProject::find($company_projects_id)->first();
|
|
|
|
$equipments = Equipment::where('company_projects_id', $company_projects_id)
|
|
->get();
|
|
|
|
foreach ($equipments as $equipment) {
|
|
$tags = [];
|
|
// Se for psv tem o id 3 e atualmente sao os unicos tipos de valvulas que tem obturador (cv),(isv) nao apresentam.
|
|
if ($equipment->equipment_type_id == 3) {
|
|
$tags = ['@Corpo', '@Flange', '@Obturador'];
|
|
} else {
|
|
$tags = ['@Corpo', '@Flange'];
|
|
}
|
|
|
|
|
|
foreach ($tags as $tag) {
|
|
$associatedEquipment = QrcodesAssociatedEquipment::where('equipment_id', $equipment->equipment_id)
|
|
->where('component_tag', 'LIKE', '%' . $tag)
|
|
->first();
|
|
|
|
if ($associatedEquipment) {
|
|
// Atualizar a coluna component_tag para ser igual à equipment_tag, mantendo a parte após o "@"
|
|
$newComponentTag = $equipment->equipment_tag . $tag;
|
|
$associatedEquipment->component_tag = $newComponentTag;
|
|
$associatedEquipment->save();
|
|
} else {
|
|
// Criar uma nova entrada
|
|
QrcodesAssociatedEquipment::create([
|
|
'equipment_id' => $equipment->equipment_id,
|
|
'component_tag' => $equipment->equipment_tag . $tag
|
|
]);
|
|
}
|
|
}
|
|
}
|
|
|
|
// Obter IDs de equipamentos ativos do projeto especificado.
|
|
$activeEquipmentIds = Equipment::where('company_projects_id', $company_projects_id)
|
|
->pluck('equipment_id')
|
|
->toArray();
|
|
|
|
// Identificar todos os equipment_id em QrcodesAssociatedEquipment.
|
|
$equipmentIdsInQrcodes = QrcodesAssociatedEquipment::pluck('equipment_id')->unique()->toArray();
|
|
|
|
// Verificar quais desses equipment_id foram desassociados de qualquer projeto na tabela Equipment.
|
|
$orphanEquipmentIds = Equipment::whereIn('equipment_id', $equipmentIdsInQrcodes)
|
|
->whereNull('company_projects_id')
|
|
->pluck('equipment_id')
|
|
->toArray();
|
|
|
|
// Excluir todas as entradas em QrcodesAssociatedEquipment para os equipment_id desassociados.
|
|
foreach ($orphanEquipmentIds as $orphanId) {
|
|
QrcodesAssociatedEquipment::where('equipment_id', $orphanId)->delete();
|
|
}
|
|
|
|
//Sempre que entrar na view ja verifica se existe 'Workstations' preparadas para esta obra.
|
|
$listWorkstations = ConstructionWorkstation::where('company_projects_id', $company_projects_id)->get();
|
|
|
|
$futherTasks = FurtherTasks::where('company_projects_id', $company_projects_id)
|
|
->get();
|
|
|
|
return view('projectsClients/workStation_3', ['step' => 3, 'numberProject' => $company_projects_id])
|
|
->with('listWorkstations', $listWorkstations)
|
|
->with('equipments', $equipments)
|
|
->with('futherTasks', $futherTasks)
|
|
->with('receiveDataCompanyProject', $receiveDataCompanyProject);
|
|
}
|
|
|
|
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) {
|
|
|
|
//Este code pode parecer repetitivo, pois antes tinha uma tabela para os 2 tipos de tarefa. TE e TC apos atualizacao ambas ficam em uma so tabela, porem por falta de tempo ainda nao foi melhorado sua logina , MAS FUNCIONA !!!!
|
|
if ($groupTasks == 'FurtherTasks') {
|
|
// Encontra a tarefa existente, se houver, para FurtherTasks
|
|
$taskAssociation = WorkstationsAssociationTasks::where('id_workstations', $workStation->id_workstations)
|
|
->where('elemental_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->elemental_tasks_id = $taskID; // Usando $taskID, que é a key
|
|
} else {
|
|
$taskAssociation->elemental_tasks_id = $taskID; // Usando $taskID, que é a key
|
|
}
|
|
$taskAssociation->company_projects_id = $workStation->company_projects_id;
|
|
}
|
|
$taskAssociation->save();
|
|
} elseif ($check == 'off' && $taskAssociation) {
|
|
$taskAssociation->delete();
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
|
|
// Redirecionar de volta com uma mensagem de sucesso
|
|
return back()->with('success', 'Posto de trabalho : ' . $workStation->name_workstations . ' atualizado com sucesso!');
|
|
}
|
|
|
|
public function processStep3(Request $request)
|
|
{
|
|
// Valide e processe os dados do formulário
|
|
// ...
|
|
session(['form_data.step3' => $request->all()]);
|
|
|
|
// Aqui, todas as etapas foram concluídas
|
|
// Você pode redirecionar o Utilizador para uma página de "Obrigado" ou processar os dados do formulário
|
|
// ...
|
|
}
|
|
|
|
public function index()
|
|
{
|
|
|
|
|
|
$results = DB::table('equipments')
|
|
->join('specific_attributes_equipament_types', 'equipments.equipment_id', '=', 'specific_attributes_equipament_types.equipment_id')
|
|
->join('general_attributes_equipaments', 'specific_attributes_equipament_types.specific_attributes_equipment_type_id', '=', 'general_attributes_equipaments.general_attributes_equipment_id')
|
|
->select('equipments.equipment_tag', 'general_attributes_equipaments.general_attributes_equipment_description', 'specific_attributes_equipament_types.specific_attributes_value')
|
|
->get();
|
|
|
|
|
|
// dd($results);
|
|
|
|
$groupedEquipments = [];
|
|
|
|
foreach ($results as $result) {
|
|
if (!isset($groupedEquipments[$result->tag])) {
|
|
$groupedEquipments[$result->tag] = [];
|
|
}
|
|
|
|
$groupedEquipments[$result->tag][] = [
|
|
'description' => $result->description,
|
|
'value' => $result->value
|
|
];
|
|
}
|
|
|
|
$equipments = DB::table('equipments')->get();
|
|
|
|
foreach ($equipments as $equipment) {
|
|
if (isset($groupedEquipments[$equipment->tag])) {
|
|
$equipment->specific_attributes = $groupedEquipments[$equipment->tag];
|
|
}
|
|
}
|
|
$allPossibleAttributes = GeneralAttributesEquipment::all()->pluck('description')->toArray();
|
|
|
|
return view('articulated_2', ['equipments' => $equipments, 'allAttributes' => $allPossibleAttributes]);
|
|
// Retorne a view com os dados
|
|
// return view('test', ['equipments' => $equipments]);
|
|
}
|
|
|
|
|
|
public function listCompanies()
|
|
{
|
|
$companies = User::where('type_users', 3)->get();
|
|
return view('projectsClients/createProject', ['companies' => $companies]);
|
|
}
|
|
|
|
|
|
public function createProject(Request $request)
|
|
{
|
|
|
|
// Validação...
|
|
$installationId = $request->input('installation_id');
|
|
|
|
if ($installationId == 'new_install') {
|
|
// Criar uma nova instalação...
|
|
$newInstallation = new Unit;
|
|
$newInstallation->installation_name = $request->input('new_company_name');
|
|
$newInstallation->address = $request->input('new_company_address');
|
|
$newInstallation->user_id = $request->input('user_id');
|
|
|
|
$newInstallation->save();
|
|
|
|
// Use o id da nova instalação.
|
|
$installationId = $newInstallation->id;
|
|
// dd($installationId);
|
|
}
|
|
|
|
$project = new CompanyProject;
|
|
|
|
$project->description_project = $request->input('description_project');
|
|
$project->n_project_ispt = $request->input('n_project_ispt');
|
|
$project->responsible_project_ispt = $request->input('responsible_project_ispt');
|
|
$project->responsible_project_company = $request->input('responsible_project_company');
|
|
$project->date_started = $request->input('date_started');
|
|
|
|
$project->installation_id = $installationId;
|
|
|
|
$project->save();
|
|
|
|
return redirect()->route('createProject')->with('success', 'Dados guardados com sucesso');
|
|
// return redirect()->route('createProject')->with('success', 'Dados guardados com sucesso');
|
|
|
|
}
|
|
|
|
public function storeProject(Request $request)
|
|
{
|
|
if ($request->input('company_id') == 'new') {
|
|
$company = new CompanyProject; // Substitua "Company" pelo nome do seu modelo de empresas
|
|
$company->name = $request->input('new_company_name');
|
|
$company->save();
|
|
|
|
$company_id = $company->id;
|
|
} else {
|
|
$company_id = $request->input('company_id');
|
|
}
|
|
|
|
// Agora, você pode usar $company_id ao criar o projeto
|
|
}
|
|
|
|
// public function getByUserNif(Request $request)
|
|
// {
|
|
|
|
// $user_id = $request->input('user_id'); //Check
|
|
// $installations = Plant::where('user_id', $user_id)->get();
|
|
|
|
// $associationUserCompany = AssociationCompanyUser::where('association_company_user_id',$user_id)->get();
|
|
|
|
// return response()->json($installations);
|
|
// }
|
|
|
|
public function getByUserNif(Request $request)
|
|
{
|
|
|
|
$companyId = $request->input('company_id'); // Considerando que este ID é na verdade o ID da empresa
|
|
|
|
// Busca as instalações associadas à empresa
|
|
$installations = Plant::where('company_id', $companyId)->get();
|
|
|
|
// Busca os usuários associados à empresa
|
|
$userIds = AssociationCompanyUser::where('company_id', $companyId)->pluck('user_id');
|
|
$users = User::whereIn('user_id', $userIds)->get();
|
|
|
|
return response()->json([
|
|
'installations' => $installations,
|
|
'users' => $users
|
|
]);
|
|
}
|
|
|
|
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 removingElementalTasksFromProject(Request $request)
|
|
{
|
|
|
|
$receiveAllEquipmentWorkHistory = EquipmentWorkHistory::where('company_projects_id', $request->numberProject)
|
|
->where('equipment_status_project', 0)
|
|
->get();
|
|
$equipmentWorkHistoryIds = $receiveAllEquipmentWorkHistory->pluck('equipmentWorkHistorys_id')->toArray();
|
|
|
|
|
|
$tasksToDelete = $request->tasks; // IDs das tarefas a serem deletadas vindo do request.
|
|
|
|
// Loop através dos IDs de EquipmentWorkHistory
|
|
foreach ($equipmentWorkHistoryIds as $historyId) {
|
|
// Recuperar todas as tarefas associadas ao EquipmentWorkHistory atual
|
|
$tasks = OrderEquipmentTasks::where('equipmentWorkHistorys_id', $historyId)->get();
|
|
|
|
// Filtrar e deletar as tarefas que estão no array $tasksToDelete
|
|
$filteredTasks = $tasks->whereIn('elemental_tasks_id', $tasksToDelete);
|
|
OrderEquipmentTasks::destroy($filteredTasks->pluck('id')); // Deletar tarefas filtradas
|
|
|
|
// Recuperar novamente as tarefas restantes após a exclusão para reordenar
|
|
$remainingTasks = OrderEquipmentTasks::where('equipmentWorkHistorys_id', $historyId)
|
|
->orderBy('execution_order')
|
|
->get();
|
|
|
|
// Reordenar as execution_order das tarefas restantes
|
|
foreach ($remainingTasks as $index => $task) {
|
|
$task->execution_order = $index + 1; // Ajustar a execution_order baseada no índice
|
|
$task->save(); // Salvar as mudanças
|
|
}
|
|
}
|
|
return back()->with('success', 'Tarefas removidas de todos os equipamentos com sucesso !!');
|
|
|
|
}
|
|
|
|
}
|