1530 lines
68 KiB
PHP
Executable File
1530 lines
68 KiB
PHP
Executable File
<?php
|
|
|
|
namespace App\Http\Controllers;
|
|
|
|
use App\Models\EquipmentWorkHistory;
|
|
use Illuminate\Http\Request;
|
|
use Illuminate\Support\Facades\DB;
|
|
use PhpOffice\PhpSpreadsheet\IOFactory;
|
|
|
|
use PhpOffice\PhpSpreadsheet\Writer\Xlsx;
|
|
use Symfony\Component\HttpFoundation\StreamedResponse;
|
|
|
|
|
|
use App\Models\User;
|
|
use App\Models\CompanyProject;
|
|
use App\Models\Unit;
|
|
use App\Models\EquipmentType;
|
|
use App\Models\Equipment;
|
|
use App\Models\Plant;
|
|
use App\Models\SpecificAttributesEquipmentType;
|
|
use App\Models\GeneralAttributesEquipment;
|
|
use App\Models\PendingEquipment;
|
|
use App\Models\AmbitsEquipment;
|
|
use App\Models\EquipmentAssociationAmbit;
|
|
use App\Models\ConstructionWorkstation;
|
|
use App\Models\ElementalTasks;
|
|
use App\Models\OrderEquipmentTasks;
|
|
use App\Models\FurtherTasks;
|
|
use App\Models\WorkstationsAssociationTasks;
|
|
use App\Models\TasksAssociationAmbits;
|
|
use App\Models\QrcodesAssociatedEquipment;
|
|
|
|
use LengthException;
|
|
|
|
// use DataTables;
|
|
|
|
|
|
class CreateProjectController extends Controller
|
|
{
|
|
public function deletePendingEquipments($pendingEquipments){
|
|
dd($pendingEquipments);
|
|
}
|
|
|
|
public function receiveUnits($numberProject)
|
|
{
|
|
$PlantData = CompanyProject::where('company_projects_id', $numberProject)->first();
|
|
|
|
if (!$PlantData) {
|
|
return response()->json([]);
|
|
}
|
|
|
|
$receiveUnits = Unit::where('plant_id', $PlantData->plant_id)->get();
|
|
|
|
// Formatar a resposta para o formato esperado pelo JavaScript
|
|
$formattedUnits = $receiveUnits->map(function ($unit) {
|
|
return [
|
|
'id' => $unit->receiveUnits, // Ajuste para o nome da sua coluna correta
|
|
'name' => $unit->unit_name // Ajuste para o nome da sua coluna correta
|
|
];
|
|
});
|
|
|
|
return response()->json($formattedUnits);
|
|
}
|
|
|
|
|
|
public function deleteFurtherTasks(Request $request)
|
|
{
|
|
$receiveDataEquipment = Equipment::where('equipment_id', $request->equipmentID)->first();
|
|
// Buscar os registros que correspondem ao equipmentID e que têm further_tasks_id nos selectedTasks
|
|
$tasksToDelete = OrderEquipmentTasks::where('equipment_id', $request->equipmentID)
|
|
->whereIn('further_tasks_id', $request->selectedTasks)
|
|
->get();
|
|
|
|
// Excluir esses registros
|
|
foreach ($tasksToDelete as $task) {
|
|
$task->delete();
|
|
}
|
|
|
|
// Se o treatmentFurtherTask for "DeleteFurtherTask", exclua os registros da tabela principal FurtherTasks
|
|
if ($request->treatmentFurtherTask == "DeleteFurtherTask") {
|
|
FurtherTasks::whereIn('further_tasks_id', $request->selectedTasks)->delete();
|
|
}
|
|
|
|
// Reordenar os registros restantes
|
|
$remainingTasks = OrderEquipmentTasks::where('equipment_id', $request->equipmentID)
|
|
->orderBy('execution_order', 'asc')
|
|
->get();
|
|
|
|
$executionOrder = 1;
|
|
foreach ($remainingTasks as $task) {
|
|
$task->execution_order = $executionOrder;
|
|
$task->save();
|
|
$executionOrder++;
|
|
}
|
|
return redirect()->back()->with('success', 'Ordem de execução do equipamento: ' . $receiveDataEquipment->equipment_tag . ' Atulizada!');
|
|
}
|
|
|
|
public function addFurtherTasks(Request $request)
|
|
{
|
|
// Recebe e organiza os dados do equipameto recebido : ($request->equipmentID) e organiza em asc de acordo com a Ordem de execução
|
|
$equipmentId = $request->equipmentID;
|
|
|
|
$tasksToReorder = OrderEquipmentTasks::where('equipment_id', $equipmentId)
|
|
->orderBy('execution_order', 'asc')
|
|
->get();
|
|
|
|
$receiveDataEquipment = Equipment::where('equipment_id', $request->equipmentID)->first();
|
|
|
|
|
|
// *Para Criar uma nova Tarefa complementar deve ser a soma dos dados das 2 tabelas para dar o numero da proxima tarefa e assim o numero da TC
|
|
// Obtenha a contagem de registros nas tabelas ElementalTasks e FurtherTasks
|
|
$elementalTasksCount = ElementalTasks::count();
|
|
$furtherTasksCount = FurtherTasks::count();
|
|
|
|
// Calcule o valor de further_tasks_id
|
|
$newFurtherTaskId = $elementalTasksCount + $furtherTasksCount + 1;
|
|
|
|
// Calcule o valor de further_tasks_name
|
|
$newFurtherTaskName = 'TC' . ($furtherTasksCount + 1);
|
|
|
|
|
|
|
|
$insertPosition = $request->ArrayListElementsTasks + 1;
|
|
|
|
// Incrementar a execution_order das tarefas após a posição de inserção
|
|
foreach ($tasksToReorder as $task) {
|
|
if ($task->execution_order >= $insertPosition) {
|
|
$task->execution_order += 1;
|
|
$task->save();
|
|
}
|
|
}
|
|
|
|
// Agora, insira a nova tarefa na posição desejada
|
|
$newOrderEquipmentTask = new OrderEquipmentTasks;
|
|
$newOrderEquipmentTask->equipment_id = $equipmentId;
|
|
$newOrderEquipmentTask->execution_order = $insertPosition;
|
|
$newOrderEquipmentTask->elemental_tasks_id = null;
|
|
|
|
// Se o selectedFurtherTaskExisting for null quer dizer que e uma TC complementar criada e nova se nao for null quer dizer que vamos criar uma TC existente.
|
|
if ($request->selectedFurtherTaskExisting == 'null') {
|
|
|
|
// Cria uma nova tarefa Complementar
|
|
$newFurtherTask = new FurtherTasks;
|
|
$newFurtherTask->further_tasks_id = $newFurtherTaskId;
|
|
$newFurtherTask->further_tasks_name = $newFurtherTaskName;
|
|
$newFurtherTask->further_tasks_description = $request->furtherTask;
|
|
$newFurtherTask->company_projects_id = $receiveDataEquipment->company_projects_id;
|
|
$newFurtherTask->save();
|
|
|
|
$newOrderEquipmentTask->further_tasks_id = $newFurtherTask->further_tasks_id;
|
|
} else {
|
|
$newOrderEquipmentTask->further_tasks_id = $request->selectedFurtherTaskExisting;
|
|
}
|
|
|
|
$newOrderEquipmentTask->inspection = 2;
|
|
$newOrderEquipmentTask->save();
|
|
|
|
return redirect()->back()->with('success', 'Ordem de execução do equipamento: ' . $receiveDataEquipment->equipment_tag . ' Atulizada!');
|
|
}
|
|
|
|
|
|
public function receiveEquipmentToAssociateTasks(Request $request)
|
|
{
|
|
// dd($request);
|
|
|
|
foreach ($request->equipment as $equipment) {
|
|
$equipmentModel = Equipment::where('equipment_id', $equipment['equipment_id'])->first();
|
|
|
|
if ($equipmentModel) {
|
|
$equipmentModel->company_projects_id = $request->receiveNumberProject;
|
|
$equipmentModel->save();
|
|
}
|
|
}
|
|
return redirect()->back()->with('success', 'Equipametos associados a Obra com Sucesso !');
|
|
}
|
|
|
|
public function receiveUnitsForExcelTemplate($numberProject)
|
|
{
|
|
$receveCompanyProject = CompanyProject::where('company_projects_id', $numberProject)->first();
|
|
$recevePlant = Plant::where('plant_id', $receveCompanyProject->plant_id)->first();
|
|
$receveUnits = Unit::where('plant_id', $recevePlant->plant_id)->get();
|
|
$filePath = public_path('templateExcel/TestTemplate.xlsx');
|
|
// Load the spreadsheet
|
|
$spreadsheet = IOFactory::load($filePath);
|
|
// Get the second sheet
|
|
$sheet = $spreadsheet->getSheet(1); // Sheet index starts from 0
|
|
$row = 1; // Row number where you want to start inserting data
|
|
foreach ($receveUnits as $unit) {
|
|
// Set value for column D
|
|
$sheet->setCellValue('D' . $row, $unit->unit_name);
|
|
$row++;
|
|
}
|
|
// Generate and return the download response
|
|
return $this->createDownloadResponse($spreadsheet, 'Valves_Template.xlsx');
|
|
}
|
|
|
|
protected function createDownloadResponse($spreadsheet, $filename)
|
|
{
|
|
// Create a writer object
|
|
$writer = new Xlsx($spreadsheet);
|
|
// Create a StreamedResponse with a callback
|
|
$response = new StreamedResponse(
|
|
function () use ($writer) {
|
|
$writer->save('php://output');
|
|
}
|
|
);
|
|
// Set headers to indicate we're sending an Excel file
|
|
$response->headers->set('Content-Type', 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
|
|
$response->headers->set('Content-Disposition', 'attachment;filename="' . $filename . '"');
|
|
$response->headers->set('Cache-Control', 'max-age=0');
|
|
|
|
return $response;
|
|
}
|
|
|
|
public function finishCreatingProject($numberProject)
|
|
{
|
|
// recebe atraves de sessao toda a vez quem entra no componente 'SelectElementalTasksInWonkstation' para selecionar as tarefas de cada Workstation
|
|
$receiveAllFurtherTasks = session('receiveAllFurtherTasks');
|
|
$receiveElementalTasks = session('receiveElementalTasks');
|
|
|
|
dd($receiveAllFurtherTasks);
|
|
|
|
// Inicializar a matriz de IDs faltantes
|
|
$missingElementalTasks = [];
|
|
$missingFurtherTasksDetails = [];
|
|
$missingWorkstations = [];
|
|
|
|
// Recebe todos os dados dos postos de Trabalho
|
|
$receiveWorkstaions = ConstructionWorkstation::where('company_projects_id', $numberProject)->get();
|
|
|
|
foreach ($receiveWorkstaions as $workstation) {
|
|
// Verifica se o ID da workstation está presente na tabela WorkstationsAssociationTasks
|
|
$exists = WorkstationsAssociationTasks::where('id_workstations', $workstation->id_workstations)->exists();
|
|
|
|
// Se não existe na tabela, adiciona à lista das workstations onde nao tem tarefas atribuidas ainda.
|
|
if (!$exists) {
|
|
$missingWorkstations[$workstation->id_workstations] = [
|
|
'name_workstations' => $workstation->name_workstations,
|
|
'nomenclature_workstation' => $workstation->nomenclature_workstation
|
|
];
|
|
}
|
|
}
|
|
|
|
// Extrai apena o id_workstations de cada um
|
|
$workstationIds = $receiveWorkstaions->pluck('id_workstations')->toArray();
|
|
|
|
// Iterar sobre cada tarefa em $receiveElementalTasks
|
|
foreach ($receiveElementalTasks as $taskGroup) {
|
|
foreach ($taskGroup as $taskId => $taskDetails) {
|
|
// Verificar se a tarefa está associada a algum id_workstations
|
|
$exists = WorkstationsAssociationTasks::whereIn('id_workstations', $workstationIds)
|
|
->where('elemental_tasks_id', $taskId)
|
|
->exists();
|
|
|
|
// Se não existe, adicionar à lista de tarefas faltantes
|
|
if (!$exists) {
|
|
$missingElementalTasks[$taskId] = $taskDetails;
|
|
}
|
|
}
|
|
}
|
|
dd($receiveAllFurtherTasks);
|
|
|
|
// Iterar sobre cada tarefa em $receiveAllFurtherTasks
|
|
foreach ($receiveAllFurtherTasks as $furtherTask) {
|
|
// Obter o ID da tarefa
|
|
$taskId = $furtherTask->further_tasks_id;
|
|
|
|
// Verificar se a tarefa está associada a algum id_workstations
|
|
$exists = WorkstationsAssociationTasks::whereIn('id_workstations', $workstationIds)
|
|
->where('elemental_tasks_id', $taskId)
|
|
->exists();
|
|
|
|
// Se não existe, adicionar à lista de tarefas faltantes
|
|
if (!$exists) {
|
|
$missingFurtherTasksDetails[$taskId] = [
|
|
'name' => $furtherTask->further_tasks_name,
|
|
'description' => $furtherTask->further_tasks_description
|
|
];
|
|
}
|
|
}
|
|
|
|
// A Partir daqui ja temos as 2 variaveis a receberem array com as tarefas que faltam ser associadas.
|
|
$allMissingTasks = [
|
|
'elemental' => $missingElementalTasks,
|
|
'further' => $missingFurtherTasksDetails,
|
|
'workstation' => $missingWorkstations
|
|
];
|
|
// Verificar se todos os arrays internos estão vazios
|
|
$isEmpty = empty($allMissingTasks['elemental']) && empty($allMissingTasks['further']) && empty($allMissingTasks['workstation']);
|
|
|
|
if (!$isEmpty) {
|
|
return redirect()->back()->with('errors', $allMissingTasks);
|
|
} else {
|
|
$project = CompanyProject::find($numberProject);
|
|
$project->order_project = 2;
|
|
$project->save();
|
|
|
|
return redirect()->route('home');
|
|
}
|
|
}
|
|
|
|
public function deleteWorkstation($name)
|
|
{
|
|
$workstation = ConstructionWorkstation::where('name_workstations', $name)->first();
|
|
$removeAcountUserWorkstation = User::where('user_name', $workstation->name_workstations)->first();
|
|
|
|
if ($workstation && $removeAcountUserWorkstation) {
|
|
$workstation->delete();
|
|
$removeAcountUserWorkstation->delete();
|
|
|
|
// pegar o número da estação de trabalho que está sendo deletada
|
|
preg_match('/workstation(\d+)-/', $workstation->name_workstations, $matches);
|
|
$deletedWorkstationNumber = $matches[1];
|
|
|
|
// pega o número do projeto da estação de trabalho que está sendo deletada
|
|
$projectNumber = explode('-', $workstation->name_workstations)[1];
|
|
|
|
// pegar todas as estações de trabalho e Utilizadors com números maiores que o deletado e renumerá-los
|
|
$workstationsToUpdate = ConstructionWorkstation::where('company_projects_id', $projectNumber)
|
|
->whereRaw("SUBSTRING_INDEX(name_workstations, '-', 1) REGEXP '^workstation[0-9]+$'")
|
|
->whereRaw("CAST(SUBSTRING(SUBSTRING_INDEX(name_workstations, '-', 1), 12) AS UNSIGNED) >= ?", [$deletedWorkstationNumber])
|
|
->orderByRaw("CAST(SUBSTRING(SUBSTRING_INDEX(name_workstations, '-', 1), 12) AS UNSIGNED) DESC")
|
|
->get();
|
|
|
|
foreach ($workstationsToUpdate as $workstationToUpdate) {
|
|
// pegar o número da estação de trabalho atual
|
|
preg_match('/workstation(\d+)-/', $workstationToUpdate->name_workstations, $matches);
|
|
$currentWorkstationNumber = $matches[1];
|
|
|
|
// atualizar nome da estação de trabalho
|
|
$workstationToUpdate->name_workstations = 'workstation' . ($currentWorkstationNumber - 1) . '-' . $projectNumber;
|
|
$workstationToUpdate->save();
|
|
|
|
// atualizar Utilizador associado
|
|
$userToUpdate = User::where('user_name', 'workstation' . $currentWorkstationNumber . '-' . $projectNumber)->first();
|
|
if ($userToUpdate) {
|
|
$userToUpdate->user_name = 'workstation' . ($currentWorkstationNumber - 1) . '-' . $projectNumber;
|
|
$userToUpdate->save();
|
|
}
|
|
}
|
|
|
|
return back()->with('success', 'Posto de Trabalho removido com sucesso!');
|
|
}
|
|
return back()->with('danger', 'Posto de Trabalho não encontrado!');
|
|
}
|
|
|
|
public function removeProjectEquipment(Request $request)
|
|
{
|
|
|
|
$equipment = Equipment::find($request->EquipmentID);
|
|
|
|
if ($request->removalType == 'total') {
|
|
$equipment->delete();
|
|
|
|
return back()->with('success', 'Equipamento Excluido com sucesso!');
|
|
} else
|
|
$equipment->company_projects_id = null;
|
|
$equipment->save();
|
|
|
|
return back()->with('success', 'Equipamento retirado da obra !');
|
|
}
|
|
public function EditEquipmentsProjects(Request $request)
|
|
{
|
|
// dd($request);
|
|
// Localiza o equipment pelo numberProject
|
|
$equipment = Equipment::find($request->equipmentId);
|
|
|
|
// Atualiza os campos
|
|
$equipment->equipment_tag = $request->tag;
|
|
$equipment->equipment_description = $request->equipmentDescription;
|
|
$equipment->equipment_serial_number = $request->serialNumberEquipment;
|
|
$equipment->equipment_brand = $request->equipmentBrand;
|
|
$equipment->equipment_model = $request->equipmentModel;
|
|
|
|
$equipment->save();
|
|
|
|
if ($request->input('attributes')) {
|
|
foreach ($request->input('attributes') as $key => $value) {
|
|
// Verifica se o valor é null e a chave é um número (correspondendo aos general_attributes_equipment_id)
|
|
if ($value == null && is_numeric($key)) {
|
|
// Procura o registro relevante em SpecificAttributesEquipmentType
|
|
$specificAttributes = SpecificAttributesEquipmentType::where('equipment_id', $request->equipmentId)
|
|
->where('general_attributes_equipment_id', $key)
|
|
->first();
|
|
|
|
// Se o registro existir, o deleta
|
|
if ($specificAttributes) {
|
|
$specificAttributes->delete();
|
|
}
|
|
}
|
|
// Se o valor não for null, atualiza ou cria um novo registro
|
|
elseif ($value !== null && is_numeric($key)) {
|
|
|
|
// Procura o registro relevante em SpecificAttributesEquipmentType
|
|
$specificAttributes = SpecificAttributesEquipmentType::where('equipment_id', $request->equipmentId)
|
|
->where('general_attributes_equipment_id', $key)
|
|
->first();
|
|
|
|
// Se o registro existir, atualiza o valor
|
|
if ($specificAttributes) {
|
|
$specificAttributes->specific_attributes_value = $value;
|
|
$specificAttributes->save();
|
|
}
|
|
// Se não existir, cria um novo
|
|
else {
|
|
// Cria um novo registro em SpecificAttributesEquipmentType
|
|
$specificAttributes = new SpecificAttributesEquipmentType();
|
|
$specificAttributes->equipment_id = $request->equipmentId;
|
|
$specificAttributes->equipment_type_id = $equipment->equipment_type_id;
|
|
$specificAttributes->general_attributes_equipment_id = $key;
|
|
$specificAttributes->specific_attributes_value = $value;
|
|
$specificAttributes->save();
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
|
|
// Se não selecionar nenhuma tarefas ele devolve um erro , pois e necessario pelo menos uma
|
|
if (!in_array('on', $request->input('ordemTasks'))) {
|
|
return redirect()->back()->with('danger', 'É necessário selecionar pelo menos uma tarefa, Para o Equipamento : ' . $equipment->equipment_tag);
|
|
}
|
|
$executionOrder = 1;
|
|
|
|
foreach ($request->input('ordemTasks') as $key => $value) {
|
|
$orderEquipmentTask = OrderEquipmentTasks::where('equipment_id', $request->equipmentId)
|
|
->where('elemental_tasks_id', $key)
|
|
->first();
|
|
|
|
if ($value == "on") {
|
|
if (!$orderEquipmentTask) {
|
|
$orderEquipmentTask = new OrderEquipmentTasks();
|
|
$orderEquipmentTask->equipment_id = $request->equipmentId;
|
|
$orderEquipmentTask->elemental_tasks_id = $key;
|
|
}
|
|
$orderEquipmentTask->execution_order = $executionOrder;
|
|
$orderEquipmentTask->save();
|
|
|
|
$executionOrder++;
|
|
} elseif ($value == "off" && $orderEquipmentTask) {
|
|
$orderEquipmentTask->delete();
|
|
}
|
|
}
|
|
|
|
|
|
$executionOrder = 1; // Reinicia a contagem de ordem de execução
|
|
$remainingOrderEquipmentTasks = OrderEquipmentTasks::where('equipment_id', $request->equipmentId)
|
|
->orderBy('execution_order', 'asc')
|
|
->get();
|
|
|
|
foreach ($remainingOrderEquipmentTasks as $orderEquipmentTask) {
|
|
$orderEquipmentTask->execution_order = $executionOrder;
|
|
$orderEquipmentTask->save();
|
|
$executionOrder++;
|
|
}
|
|
|
|
$orderTasks = OrderEquipmentTasks::where('equipment_id', $request->equipmentId)
|
|
->orderBy('execution_order', 'asc')
|
|
->get();
|
|
|
|
$taskExecutionOrders = [];
|
|
foreach ($orderTasks as $task) {
|
|
$taskExecutionOrders[$task->elemental_tasks_id] = $task->execution_order;
|
|
}
|
|
|
|
// Retorna uma resposta
|
|
return redirect()->route('articulated_2', ['projectID' => $request->numberProject])
|
|
->with('success', 'Equipamento ' . $equipment->equipment_tag . ' Editado com Sucesso!!!')
|
|
->with('taskExecutionOrders', $taskExecutionOrders);
|
|
}
|
|
|
|
public function showJson($id)
|
|
{
|
|
$attributes = SpecificAttributesEquipmentType::where('equipment_id', $id)->get();
|
|
$OrdemTasks = OrderEquipmentTasks::where('equipment_id', $id)->get();
|
|
$allElementalTasks = ElementalTasks::all();
|
|
|
|
return response()->json([
|
|
'attributes' => $attributes,
|
|
'OrdemTasks' => $OrdemTasks,
|
|
'allElementalTasks' => $allElementalTasks
|
|
]);
|
|
}
|
|
|
|
public function receveTasksWorkstationPlanning($WorkstationId)
|
|
{
|
|
$workstationsAssociationTasks = WorkstationsAssociationTasks::where('id_workstations', $WorkstationId)->get();
|
|
|
|
return response()->json([
|
|
'workstationsAssociationTasks' => $workstationsAssociationTasks
|
|
]);
|
|
}
|
|
|
|
|
|
public function createWorkStations(Request $request)
|
|
{
|
|
// Pega o número de estações de trabalho do request
|
|
$numberWorkstations = $request->numberWorkstations;
|
|
|
|
// Pega o número do projeto do request
|
|
$numberProject = $request->numberProject;
|
|
|
|
$listWorkstations = ConstructionWorkstation::where('company_projects_id', $numberProject)->get();
|
|
$receveProjectCompanyNumber = CompanyProject::where('company_projects_id', $numberProject)->first();
|
|
|
|
// Pega o último elemento da lista
|
|
$lastWorkstation = $listWorkstations->last();
|
|
|
|
|
|
// Se houver uma estação de trabalho anterior, extrai o número dela
|
|
$startNumber = 1;
|
|
if ($lastWorkstation) {
|
|
$parts = explode('-', $lastWorkstation->name_workstations);
|
|
$startNumber = intval(str_replace('workstation', '', $parts[0])) + 1;
|
|
}
|
|
|
|
// Loop para criar as estações de trabalho e seus logins
|
|
for ($i = $startNumber; $i < $startNumber + $numberWorkstations; $i++) {
|
|
$workstation = new ConstructionWorkstation();
|
|
$workstation->name_workstations = 'workstation' . $i . '-' . $numberProject;
|
|
$workstation->company_projects_id = $numberProject;
|
|
$workstation->save();
|
|
|
|
preg_match('/workstation(\d+)-/', $workstation->name_workstations, $matches);
|
|
$receiveNumberWorkstation = $matches[1];
|
|
|
|
//Apos criar a Workstation vamos criar um login para pode aceder os postos de trabalho na obra
|
|
$loginWorkStation = new User;
|
|
$loginWorkStation->user_name = $workstation->name_workstations;
|
|
$loginWorkStation->email = $receveProjectCompanyNumber->project_company_number . '-' . $receiveNumberWorkstation . '@isptgroup.com';
|
|
$loginWorkStation->password = bcrypt($receveProjectCompanyNumber->project_company_number . '-' . $receiveNumberWorkstation);
|
|
$loginWorkStation->type_users = 5;
|
|
$loginWorkStation->user_nif = $receveProjectCompanyNumber->project_company_number . '-' . $receiveNumberWorkstation;
|
|
$loginWorkStation->save();
|
|
}
|
|
|
|
// Redireciona para onde você quiser após a criação das workstations
|
|
return redirect()->route('workStation_3', ['id' => $request->numberProject])
|
|
->with('success', $numberWorkstations . ' Postos de Trabalho criados !!!')
|
|
->with('listWorkstations', $listWorkstations);
|
|
}
|
|
|
|
|
|
// Funcao apenas para retornar os dados necessarios para a view criar uma Obra.
|
|
public function createProjectForStep1()
|
|
{
|
|
$companies = User::where('type_users', 3)->get();
|
|
// Apos terminar não vai ficar step 1
|
|
return view('projectsClients/createProject', ['step' => 1], ['companies' => $companies]);
|
|
}
|
|
|
|
// Progress Bar
|
|
//Devolve para a primeira para na Descrição do projecto apenas user com ID 3, quer dizer que apenas as "empresas"
|
|
public function showStep1($company_projects_id)
|
|
{
|
|
// $projects = CompanyProject::find($company_projects_id);
|
|
|
|
$projects = CompanyProject::with('user')->find($company_projects_id);
|
|
// dd($projects->user);
|
|
|
|
$companies = User::where('type_users', 3)->get();
|
|
|
|
return view('projectsClients/projectDetails_1', ['step' => 1], ['companies' => $companies])
|
|
->with('projects', $projects);
|
|
}
|
|
|
|
// Se forem alterados dados dos Detalhes da Obra, vai ser alterado
|
|
public function EditprocessStep1(Request $request)
|
|
{
|
|
}
|
|
|
|
public function removePendingEquipment($id)
|
|
{
|
|
$equipment = PendingEquipment::findOrFail($id);
|
|
$equipment->delete();
|
|
return back()->with('success', 'Equipamento pendente removido com sucesso!');
|
|
}
|
|
|
|
public function CreateNewEquipmentFromPendingEquipment(Request $request, $id)
|
|
{
|
|
$checkPendingEquipment = PendingEquipment::findOrFail($id);
|
|
|
|
$counter = 2;
|
|
$baseTag = $checkPendingEquipment->pending_equipment_tag;
|
|
$baseDescription = $checkPendingEquipment->pending_equipment_description;
|
|
|
|
// Ciclo para verificar se ja existe um equipamento com o mesmo nome se existir vai criando com o contador iniciado a partir de (2)
|
|
while (Equipment::where('equipment_tag', $baseTag . "({$counter})")->orWhere('equipment_description', $baseDescription . "({$counter})")->exists()) {
|
|
$counter++;
|
|
}
|
|
|
|
$newEquipment = new Equipment;
|
|
$newEquipment->unit_id = $checkPendingEquipment->pending_equipment_unit_id;
|
|
$newEquipment->equipment_type_id = $checkPendingEquipment->pending_equipment_type_id;
|
|
$newEquipment->equipment_tag = $baseTag . "({$counter})";
|
|
$newEquipment->equipment_description = $baseDescription . "({$counter})";
|
|
$newEquipment->equipment_serial_number = $checkPendingEquipment->pending_equipment_serial_number;
|
|
$newEquipment->equipment_brand = $checkPendingEquipment->pending_equipment_brand;
|
|
$newEquipment->equipment_model = $checkPendingEquipment->pending_equipment_model;
|
|
$newEquipment->company_projects_id = $checkPendingEquipment->pending_company_projects_id;
|
|
$newEquipment->save();
|
|
|
|
$receiveEquipmentID = $newEquipment->equipment_id;
|
|
|
|
$newEquipmentAssociationAmbits = new EquipmentAssociationAmbit;
|
|
$newEquipmentAssociationAmbits->equipment_type_id = $newEquipment->equipment_type_id;
|
|
$newEquipmentAssociationAmbits->ambits_id = $request->EquipmentAmbit;
|
|
$newEquipmentAssociationAmbits->equipment_id = $receiveEquipmentID;
|
|
$newEquipmentAssociationAmbits->save();
|
|
|
|
|
|
|
|
$checkPendingEquipment->delete();
|
|
|
|
return back()->with('success', 'Equipamento ' . $newEquipment->equipment_tag . ' criado com sucesso');
|
|
}
|
|
|
|
|
|
public function processStep1(Request $request)
|
|
{
|
|
// Validação...
|
|
$installationId = $request->input('installation_id');
|
|
|
|
if ($installationId == 'new_install') {
|
|
|
|
// Criar uma nova instalação...
|
|
$newInstallation = new Plant;
|
|
|
|
$newInstallation->plant_name = $request->input('new_company_name');
|
|
$newInstallation->plant_address = $request->input('new_company_address');
|
|
$newInstallation->user_id = $request->input('user_id');
|
|
|
|
$newInstallation->save();
|
|
|
|
// Use o id da nova instalação.
|
|
$installationId = $newInstallation->plant_id;
|
|
}
|
|
|
|
$project = new CompanyProject;
|
|
|
|
$project->company_project_description = $request->input('description_project');
|
|
$project->project_ispt_number = $request->input('n_project_ispt');
|
|
$project->project_company_number = $request->input('project_company_number');
|
|
$project->project_ispt_responsible = $request->input('responsible_project_ispt');
|
|
$project->project_company_responsible = $request->input('responsible_project_company');
|
|
|
|
// Verifica se e igual a nulo , se for usa a data ja existente
|
|
if ($request->date_started === null) {
|
|
$project->date_started = $request->input('date_started_present');
|
|
} else
|
|
$project->date_started = $request->input('date_started');
|
|
|
|
$project->plant_id = $installationId;
|
|
$project->order_project = 1;
|
|
|
|
$project->save();
|
|
|
|
session(['form_data.step1' => $request->all()]);
|
|
|
|
// // Redirecione o Utilizador para a próxima etapa
|
|
// return redirect('/articulated_2')
|
|
// ->with('project', $project)
|
|
// ->with('success', 'Dados guardados com sucesso');
|
|
return redirect()->route('articulated_2', ['id' => $project->company_projects_id])
|
|
->with('success', 'Detalhes, Projecto criado com sucesso');
|
|
}
|
|
|
|
public function showStep2($company_projects_id)
|
|
{
|
|
// Verifique se a etapa 1 foi concluída
|
|
|
|
// if (!session('form_data.step1')) {
|
|
// return redirect('/createProject');
|
|
// }
|
|
|
|
//recebe o Id de Plant vai devolver todos os equipamentos relacionados a esta Instalação(plant)
|
|
// Carregue o projeto com o id fornecido
|
|
$project = CompanyProject::find($company_projects_id);
|
|
|
|
$numberProject = $project->company_projects_id;
|
|
|
|
$typeEquipments = EquipmentType::all();
|
|
|
|
//Retorna todas as Fabricas Unit, com base na Instalação
|
|
$checkUnits = DB::table('units')
|
|
->join('plants', 'units.plant_id', '=', 'plants.plant_id')
|
|
->join('company_projects', 'plants.plant_id', '=', 'company_projects.plant_id')
|
|
->select('units.*')
|
|
->where('company_projects.company_projects_id', '=', $company_projects_id)
|
|
->get();
|
|
|
|
//Retorna todos os Equipamentos, com base na instalcao do projecto
|
|
$checkEquipments = DB::table('equipments')
|
|
->join('units', 'equipments.unit_id', '=', 'units.unit_id')
|
|
->join('plants', 'units.plant_id', '=', 'plants.plant_id')
|
|
->select('equipments.*') // Seleciona todas as colunas da tabela 'equipments'
|
|
->where('plants.plant_id', '=', $project['plant_id']) // Filtra baseado no 'plant_id'
|
|
->get();
|
|
|
|
// Para listar os equipamentos vinculados na obra, buscamos suas associações gerais entre suas tabelas , ou seja a : fabrica(unit), tipo de equipamento e o Âmbito para se realizar a tarefas pretendida neste obra.
|
|
$listEquipmentsProjects = Equipment::with([
|
|
'unit',
|
|
'equipmentType',
|
|
// 'equipmentAssociationAmbit.ambitsEquipment',
|
|
'specificAttributes' => function ($query) {
|
|
$query->orderBy('specific_attributes_value', 'asc');
|
|
}
|
|
])
|
|
->where('company_projects_id', $company_projects_id)
|
|
->get();
|
|
|
|
dd($listEquipmentsProjects);
|
|
|
|
$pendingEquipments = PendingEquipment::where('pending_company_projects_id', $numberProject)->get();
|
|
|
|
if (!$pendingEquipments->isEmpty()) {
|
|
// Retornamos para a view 'step' => 2 indicando conclusao da primeira parte, $numberProject para associacao de equipamentos a esta obra, alem de todos os equipamentos e fabricao ja existente com base na Instalação que se iniciou a obra.
|
|
return view('projectsClients/articulated_2', ['step' => 2, 'numberProject' => $numberProject])
|
|
->with('danger', 'Equipamentos Pendentes: ' . count($pendingEquipments))
|
|
->with('pendingEquipments', $pendingEquipments)
|
|
->with('listEquipmentsProjects', $listEquipmentsProjects)
|
|
->with('typeEquipments', $typeEquipments)
|
|
->with('checkEquipments', $checkEquipments)
|
|
->with('checkUnits', $checkUnits)
|
|
->with('receiveNumberProject', $project);
|
|
}
|
|
return view('projectsClients/articulated_2', ['step' => 2, 'numberProject' => $numberProject])
|
|
->with('listEquipmentsProjects', $listEquipmentsProjects)
|
|
->with('typeEquipments', $typeEquipments)
|
|
->with('checkEquipments', $checkEquipments)
|
|
->with('checkUnits', $checkUnits)
|
|
->with('receiveNumberProject', $project);
|
|
}
|
|
|
|
public function createEquipmentManual(Request $request)
|
|
{
|
|
// EquipmentAmbit
|
|
// *** Recebe a Instalação(Plant), com base no número da Obra Criada
|
|
$receivePlant = DB::table('plants')
|
|
->join('company_projects', 'company_projects.plant_id', 'plants.plant_id')
|
|
->select('plants.plant_id')
|
|
->where('company_projects.company_projects_id', '=', $request->numberProject)
|
|
->get();
|
|
|
|
//recebe a lista de todos os equipmentos relacionados a obra que se esta a criar.
|
|
$listEquipmentsProjects = DB::table('equipments')
|
|
->select('equipments.*')
|
|
->where('equipments.company_projects_id', '=', $request->numberProject)
|
|
->get();
|
|
|
|
// Verifica se ja existe um equipamento com as as caracteristicas : tag,unit_id, iguais ao que pretendemos criar
|
|
$existingEquipment = Equipment::firstWhere([
|
|
'equipment_tag' => $request->tag,
|
|
'unit_id' => $request->unit_id
|
|
]);
|
|
|
|
if ($existingEquipment) {
|
|
return redirect()->route('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;
|
|
|
|
$newEquipmentWorkHistorys->equipment_id = $equipmentID;
|
|
$newEquipmentWorkHistorys->ispt_number = 0;
|
|
$newEquipmentWorkHistorys->company_projects_id = $request->numberProject;
|
|
|
|
$newEquipmentWorkHistorys->save();
|
|
|
|
$equipmentWorkHistorysID = $newEquipmentWorkHistorys->equipmentWorkHistorys_id;
|
|
|
|
// Verifica os campos do Card_do tipo de valvula selecionado (Ex: psv_card) e de acordo com os campos preenchidos se for de atributos especificos, ele compara o 'name' dos inputs com os 'general_attributes_equipment_description' da tabela : GeneralAttributesEquipment e associa
|
|
$checkAtributs = GeneralAttributesEquipment::whereIn('general_attributes_equipment_description', array_keys($request->all()))
|
|
->pluck('general_attributes_equipment_id', 'general_attributes_equipment_description')
|
|
->toArray();
|
|
|
|
// Recebe esta associacao, e cria um array para cada 'name'(inputs) igual ao 'general_attributes_equipment_description', contanto que seu valor(input) seja diferente de *NULL, assim o "$receivesAssociationAttributes" recebe o id de acordo com a tabela , o nome de acordo com a tabela e o valor do $request recebido associado ao campo
|
|
$receivesAssociationAttributes = [];
|
|
foreach ($checkAtributs as $description => $id) {
|
|
if ($request[$description] !== null) {
|
|
$receivesAssociationAttributes[] = [
|
|
'general_attributes_equipment_id' => $id,
|
|
'general_attributes_equipment_description' => $description,
|
|
'value' => $request[$description]
|
|
];
|
|
}
|
|
}
|
|
// Para cada um dos Arrays criados acima, vai criar os novos dados na tabela 'SpecificAttributesEquipmentType'
|
|
foreach ($receivesAssociationAttributes as $receivesAssociationAttribute) {
|
|
|
|
$AddAtributsEquipments = new SpecificAttributesEquipmentType;
|
|
$AddAtributsEquipments->equipment_id = $equipmentID;
|
|
$AddAtributsEquipments->equipment_type_id = $request->equipmentTypeId;
|
|
$AddAtributsEquipments->general_attributes_equipment_id = $receivesAssociationAttribute['general_attributes_equipment_id'];
|
|
$AddAtributsEquipments->specific_attributes_value = $receivesAssociationAttribute['value'];
|
|
|
|
$AddAtributsEquipments->save();
|
|
}
|
|
//Criar associacao do equipamento ao Âmbito
|
|
$AssociationEquipmentAmbit = new EquipmentAssociationAmbit;
|
|
$AssociationEquipmentAmbit->equipment_type_id = $request->equipmentTypeId;
|
|
$AssociationEquipmentAmbit->ambits_id = $request->EquipmentAmbit;
|
|
$AssociationEquipmentAmbit->equipmentWorkHistorys_id = $equipmentWorkHistorysID;
|
|
|
|
$AssociationEquipmentAmbit->save();
|
|
|
|
$execution_order = 1;
|
|
|
|
//Recebe a tabela com as associoacoes entre Âmbitos e tarefas Elementares
|
|
$TasksAssociationAmbits = TasksAssociationAmbits::all()->where('ambits_equipment_id', $AssociationEquipmentAmbit->ambits_id);
|
|
|
|
foreach ($TasksAssociationAmbits as $TasksAssociationAmbit) {
|
|
$JoinsEquipmentsWithTasks = new OrderEquipmentTasks;
|
|
$JoinsEquipmentsWithTasks->equipmentWorkHistorys_id = $equipmentWorkHistorysID;
|
|
$JoinsEquipmentsWithTasks->execution_order = $execution_order++;
|
|
$JoinsEquipmentsWithTasks->elemental_tasks_id = $TasksAssociationAmbit->elemental_tasks_id;
|
|
$JoinsEquipmentsWithTasks->further_tasks_id = null;
|
|
$JoinsEquipmentsWithTasks->inspection = 2;
|
|
$JoinsEquipmentsWithTasks->save();
|
|
}
|
|
|
|
// O $request->numberProject e sempre necessario retornar para indicar a obra que se esta modificando...
|
|
return redirect()->route('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;
|
|
|
|
// Inicializa o contador para ispt_number
|
|
$isptNumber = 1;
|
|
|
|
// Certifique-se de que um arquivo foi enviado
|
|
if ($file) {
|
|
// Carregue o arquivo Excel
|
|
$spreadsheet = IOFactory::load($file->path());
|
|
|
|
// Obtenha a primeira planilha, onde fica os nomes chaves para associar as tabelas : 'general_attributes_equipaments' ,'equipments' e 'equipmentWorkHistorys'
|
|
$worksheet = $spreadsheet->getSheet(0);
|
|
|
|
// Transforme os dados da planilha em um array
|
|
$data = $worksheet->toArray();
|
|
|
|
|
|
// Retorna um array com todos os names preenchidos na primeira linha do template de Excel
|
|
$nomesColunas = $data[0];
|
|
|
|
// dd($data);
|
|
|
|
$countPendingEquipments = 0;
|
|
$countNewEquipment = 0;
|
|
|
|
$linhasIgnoradas = [];
|
|
|
|
// Comece a partir da sexta linha do template os dados dos Equipamentos
|
|
for ($i = 6; $i < count($data); $i++) {
|
|
|
|
$dadosLinha = $data[$i];
|
|
|
|
// Verifica se os 5 primeiros campos essenciais estao preenchidos, um deles não estiver preenchido ele ignora e não cria o equipamento
|
|
// $isEmpty = false;
|
|
// for ($j = 0; $j < 5; $j++) {
|
|
// if (empty($dadosLinha[$j])) {
|
|
// $isEmpty = true;
|
|
// break;
|
|
// }
|
|
// }
|
|
// if ($isEmpty) {
|
|
// continue;
|
|
// }
|
|
|
|
$dadosLinha = $data[$i];
|
|
|
|
// Verifica se a coluna 'fábrica' (primeiro campo) está vazia
|
|
if (empty($dadosLinha[0])) {
|
|
// Se a coluna 'fábrica' estiver vazia, pule para a próxima linha
|
|
continue;
|
|
}
|
|
|
|
// Verifica se os 5 primeiros campos essenciais estão preenchidos
|
|
for ($j = 0; $j < 5; $j++) {
|
|
if (empty($dadosLinha[$j])) {
|
|
// Se um campo (exceto 'fábrica') estiver vazio, adicione a linha e o índice do campo vazio às linhas ignoradas
|
|
$linhasIgnoradas[] = [
|
|
'linha' => $i,
|
|
'campoVazio' => $nomesColunas[$j] // ou simplesmente $j se não tiver o nome da coluna
|
|
];
|
|
continue 2; // Pula para a próxima linha
|
|
}
|
|
}
|
|
|
|
|
|
// Em cada um das linhas horizontais do excel, vai se guardar a 'key' vinculada ao valor do campo preenchido ou seja a 'key' vai ter o mesmo nome de um dos dados da tabela 'general_attributes_equipaments' na coluna : general_attributes_equipment_description, assim sendo mais facil implementar na tabela : specific_attributes_equipament_types
|
|
$juntarArrays = array_combine($nomesColunas, $dadosLinha);
|
|
|
|
// vai guardar todos os campos de possiveis novos equipamentos, cada um em um array para multiplos inserts, na base de dados
|
|
$datas = array_filter($juntarArrays, function ($chave) {
|
|
return !empty($chave);
|
|
}, ARRAY_FILTER_USE_KEY);
|
|
|
|
//Indentifica qual o tipo de equipamento selecionado de acordo com a tabela EquipmentType
|
|
$equipmentType = EquipmentType::where('equipment_type_name', $datas['equipment_type_name'])->first();
|
|
|
|
$checkFactory = Unit::where('unit_name', $datas['unit'])->first();
|
|
|
|
// Antes de criar o novo equipamento, verifique se já existe um equipamento
|
|
// com o mesmo factory_id e tag.
|
|
$existingEquipment = Equipment::where('unit_id', $checkFactory->unit_id)
|
|
->where('equipment_tag', $datas['equipment_tag'])
|
|
->first();
|
|
|
|
if ($existingEquipment) {
|
|
|
|
// Se o equipamento existir, crie o novo equipamento na tabela pending_equipaments.
|
|
$pendingEquipament = new PendingEquipment;
|
|
|
|
// Defina os atributos do pendingEquipament conforme necessário.
|
|
$pendingEquipament->pending_equipment_unit_id = $checkFactory->unit_id;
|
|
$pendingEquipament->pending_equipment_type_id = $equipmentType->equipment_type_id;
|
|
$pendingEquipament->pending_equipment_tag = $datas['tag'];
|
|
$pendingEquipament->pending_equipment_description = $datas['equipment_Description'];
|
|
$pendingEquipament->pending_equipment_serial_number = $datas['n_serie'];
|
|
$pendingEquipament->pending_equipment_brand = $datas['modelo'];
|
|
$pendingEquipament->pending_company_projects_id = $company_projects_id;
|
|
$pendingEquipament->save();
|
|
|
|
// Incremente o contador de PendingEquipments
|
|
$countPendingEquipments++;
|
|
|
|
// Continue com o próximo loop.
|
|
continue;
|
|
}
|
|
|
|
$newEquipament = new Equipment;
|
|
|
|
$newEquipament->unit_id = $checkFactory->unit_id;
|
|
$newEquipament->equipment_type_id = $equipmentType->equipment_type_id;
|
|
$newEquipament->equipment_Description = $datas['equipment_description'];
|
|
$newEquipament->equipment_tag = $datas['equipment_tag'];
|
|
$newEquipament->equipment_serial_number = $datas['equipment_serial_number'];
|
|
$newEquipament->equipment_brand = $datas['equipment_brand'];
|
|
$newEquipament->equipment_model = $datas['equipment_model'];
|
|
$newEquipament->ispt_number = $isptNumber;
|
|
$newEquipament->company_projects_id = $company_projects_id;
|
|
|
|
$newEquipament->save();
|
|
|
|
$countNewEquipment++;
|
|
|
|
$isptNumber++;
|
|
|
|
// Guardo os valores de 'id' e do 'tipo de equipamento' que nosso novo equipamento acabado de criar
|
|
$receveEquipment_ID = $newEquipament->equipment_id;
|
|
$receveEquipament_type_ID = $newEquipament->equipment_type_id;
|
|
|
|
|
|
$ambit = AmbitsEquipment::where('ambits_description', $datas['ambit'])->first();
|
|
|
|
if ($ambit) {
|
|
$ambit_id = $ambit->ambits_id;
|
|
}
|
|
|
|
//Criar associacao do equipamento ao Âmbito
|
|
$AssociationEquipmentAmbit = new EquipmentAssociationAmbit;
|
|
$AssociationEquipmentAmbit->equipment_type_id = $receveEquipament_type_ID;
|
|
$AssociationEquipmentAmbit->ambits_id = $ambit_id;
|
|
$AssociationEquipmentAmbit->equipment_id = $receveEquipment_ID;
|
|
$AssociationEquipmentAmbit->save();
|
|
|
|
$execution_order = 1;
|
|
|
|
//Recebe a tabela com as associoacoes entre Âmbitos e tarefas Elementares
|
|
$TasksAssociationAmbits = TasksAssociationAmbits::all()->where('ambits_equipment_id', $AssociationEquipmentAmbit->ambits_id);
|
|
|
|
foreach ($TasksAssociationAmbits as $TasksAssociationAmbit) {
|
|
$JoinsEquipmentsWithTasks = new OrderEquipmentTasks;
|
|
$JoinsEquipmentsWithTasks->equipment_id = $receveEquipment_ID;
|
|
$JoinsEquipmentsWithTasks->execution_order = $execution_order++;
|
|
$JoinsEquipmentsWithTasks->elemental_tasks_id = $TasksAssociationAmbit->elemental_tasks_id;
|
|
$JoinsEquipmentsWithTasks->further_tasks_id = null;
|
|
// 2 vai significar 'nao' e 1 'sim'
|
|
$JoinsEquipmentsWithTasks->inspection = 2;
|
|
$JoinsEquipmentsWithTasks->save();
|
|
}
|
|
|
|
|
|
$generalAttributes = GeneralAttributesEquipment::all();
|
|
|
|
|
|
foreach ($generalAttributes as $generalAttribute) {
|
|
// Verifica se a chave existe em $datas, comparando com os dados da tabela : GeneralAttributesEquipment assim adicionando todos diferentes de NULL relacionados com o equipamento acabado de cria
|
|
if (isset($datas[$generalAttribute->general_attributes_equipment_description])) {
|
|
|
|
$specificAttribute = new SpecificAttributesEquipmentType;
|
|
$specificAttribute->equipment_id = $receveEquipment_ID;
|
|
$specificAttribute->equipment_type_id = $receveEquipament_type_ID;
|
|
$specificAttribute->general_attributes_equipment_id = $generalAttribute->general_attributes_equipment_id;
|
|
// Atribui o valor da chave correspondente em $datas
|
|
$specificAttribute->specific_attributes_value = $datas[$generalAttribute->general_attributes_equipment_description];
|
|
|
|
$specificAttribute->save();
|
|
}
|
|
}
|
|
}
|
|
dd($linhasIgnoradas);
|
|
|
|
|
|
$pendingEquipments = PendingEquipment::where('pending_company_projects_id', $request->numberProject)->get();
|
|
|
|
// $pendingEquipments = session('pendingEquipments');
|
|
if ($countPendingEquipments != 0) {
|
|
// return redirect()->route('articulated_2')->with('Danger', 'Equipamentos Pendentes')->with('listValves', $listValves)->with('pendingEquipments', $pendingEquipments);
|
|
return redirect()->route('articulated_2', ['projectID' => $request->numberProject])
|
|
->with('danger', 'Equipamentos Pendentes criados : ' . $countPendingEquipments)
|
|
->with('pendingEquipments', $pendingEquipments);
|
|
// ->with('success', 'Equipamentos Criados :' . count($listValves))
|
|
}
|
|
return redirect()->route('articulated_2', ['projectID' => $request->numberProject])
|
|
->with('success', 'Equipamentos Criados :' . $countNewEquipment);
|
|
}
|
|
|
|
//Nao chega aqui ainda pois volta para a pagina com dados ja carregados.
|
|
|
|
session(['form_data.step2' => $request->all()]);
|
|
|
|
// Redirecione o Utilizador para a próxima etapa
|
|
return redirect('/workStation_3');
|
|
}
|
|
|
|
public function showStep3($company_projects_id)
|
|
{
|
|
$equipments = Equipment::where('company_projects_id', $company_projects_id)
|
|
->get();
|
|
|
|
foreach ($equipments as $equipment) {
|
|
$tags = [];
|
|
if ($equipment->equipment_type_id == 3) {
|
|
$tags = ['@Corpo', '@Flange', '@Obturador'];
|
|
} elseif ($equipment->equipment_type_id == 1) {
|
|
$tags = ['@Corpo', '@Flange'];
|
|
}
|
|
|
|
foreach ($tags as $tag) {
|
|
$associatedEquipment = QrcodesAssociatedEquipment::where('equipment_id', $equipment->equipment_id)
|
|
->where('component_tag', 'LIKE', '%' . $tag)
|
|
->first();
|
|
|
|
if ($associatedEquipment) {
|
|
// Atualizar a coluna component_tag para ser igual à equipment_tag, mantendo a parte após o "@"
|
|
$newComponentTag = $equipment->equipment_tag . $tag;
|
|
$associatedEquipment->component_tag = $newComponentTag;
|
|
$associatedEquipment->save();
|
|
} else {
|
|
// Criar uma nova entrada
|
|
QrcodesAssociatedEquipment::create([
|
|
'equipment_id' => $equipment->equipment_id,
|
|
'component_tag' => $equipment->equipment_tag . $tag
|
|
]);
|
|
}
|
|
}
|
|
}
|
|
|
|
// 3. Verificar se há algum equipment_id em QrcodesAssociatedEquipment que não existe mais em Equipment e, se sim, excluí-lo.
|
|
$allEquipmentIds = Equipment::where('company_projects_id', $company_projects_id)->pluck('equipment_id')->toArray();
|
|
$orphanedEntries = QrcodesAssociatedEquipment::whereNotIn('equipment_id', $allEquipmentIds)->get();
|
|
|
|
foreach ($orphanedEntries as $orphanedEntry) {
|
|
$orphanedEntry->delete();
|
|
}
|
|
|
|
|
|
|
|
//Sempre que entrar na view ja verifica se existe 'Workstations' preparadas para esta obra.
|
|
$listWorkstations = ConstructionWorkstation::where('company_projects_id', $company_projects_id)->get();
|
|
|
|
$futherTasks = FurtherTasks::where('company_projects_id', $company_projects_id)
|
|
->get();
|
|
|
|
return view('projectsClients/workStation_3', ['step' => 3, 'numberProject' => $company_projects_id])
|
|
->with('listWorkstations', $listWorkstations)
|
|
->with('equipments', $equipments)
|
|
->with('futherTasks', $futherTasks);
|
|
}
|
|
|
|
public function workstationsAssociationTasks(Request $request)
|
|
{
|
|
// dd($request);
|
|
|
|
$workStation = ConstructionWorkstation::where('id_workstations', $request->idWorkStation)->first();
|
|
|
|
// Trocar o nome se for diferente do recebido
|
|
if ($workStation) {
|
|
$workStation->nomenclature_workstation = $request->nameWorkstation;
|
|
$workStation->save();
|
|
}
|
|
|
|
// Atualizar a lista de tipos de tarefas para incluir os novos grupos
|
|
$taskTypes = ['generalTasks', '1', '2', '3', 'FurtherTasks'];
|
|
|
|
foreach ($taskTypes as $groupTasks) {
|
|
if (isset($request[$groupTasks])) { // Checar se esse grupo de tarefas existe no request
|
|
foreach ($request[$groupTasks] as $taskID => $check) {
|
|
|
|
if ($groupTasks == 'FurtherTasks') {
|
|
// Encontra a tarefa existente, se houver, para FurtherTasks
|
|
$taskAssociation = WorkstationsAssociationTasks::where('id_workstations', $workStation->id_workstations)
|
|
->where('further_tasks_id', $taskID)
|
|
->where('company_projects_id', $workStation->company_projects_id)
|
|
->first();
|
|
} else {
|
|
// Encontra a tarefa existente, se houver, para os outros grupos
|
|
$taskAssociation = WorkstationsAssociationTasks::where('id_workstations', $workStation->id_workstations)
|
|
->where('elemental_tasks_id', $taskID)
|
|
->where('company_projects_id', $workStation->company_projects_id)
|
|
->first();
|
|
}
|
|
|
|
if ($check == 'on') {
|
|
if (!$taskAssociation) {
|
|
$taskAssociation = new WorkstationsAssociationTasks;
|
|
$taskAssociation->id_workstations = $workStation->id_workstations;
|
|
if ($groupTasks == 'FurtherTasks') {
|
|
$taskAssociation->further_tasks_id = $taskID; // Usando $taskID, que é a key
|
|
} else {
|
|
$taskAssociation->elemental_tasks_id = $taskID; // Usando $taskID, que é a key
|
|
}
|
|
$taskAssociation->company_projects_id = $workStation->company_projects_id;
|
|
}
|
|
$taskAssociation->save();
|
|
} elseif ($check == 'off' && $taskAssociation) {
|
|
$taskAssociation->delete();
|
|
}
|
|
}
|
|
}
|
|
}
|
|
|
|
|
|
// Redirecionar de volta com uma mensagem de sucesso
|
|
return back()->with('success', 'Posto de trabalho : ' . $workStation->name_workstations . ' atualizado com sucesso!');
|
|
}
|
|
|
|
public function processStep3(Request $request)
|
|
{
|
|
// Valide e processe os dados do formulário
|
|
// ...
|
|
session(['form_data.step3' => $request->all()]);
|
|
|
|
// Aqui, todas as etapas foram concluídas
|
|
// Você pode redirecionar o Utilizador para uma página de "Obrigado" ou processar os dados do formulário
|
|
// ...
|
|
}
|
|
|
|
public function index()
|
|
{
|
|
// $results = DB::table('equipaments')
|
|
// ->join('specific_attributes_equipament_types', 'equipaments.equipment_ID', '=', 'specific_attributes_equipament_types.tb_equipament_id')
|
|
// ->join('general_attributes_equipaments', 'specific_attributes_equipament_types.specific_Attributes_Equipment_Type_ID', '=', 'general_attributes_equipaments.general_Attributes_Equipment_ID')
|
|
// ->select('equipaments.tag', 'general_attributes_equipaments.description', 'specific_attributes_equipament_types.value')
|
|
// ->get();
|
|
|
|
$results = DB::table('equipments')
|
|
->join('specific_attributes_equipament_types', 'equipments.equipment_id', '=', 'specific_attributes_equipament_types.equipment_id')
|
|
->join('general_attributes_equipaments', 'specific_attributes_equipament_types.specific_attributes_equipment_type_id', '=', 'general_attributes_equipaments.general_attributes_equipment_id')
|
|
->select('equipments.equipment_tag', 'general_attributes_equipaments.general_attributes_equipment_description', 'specific_attributes_equipament_types.specific_attributes_value')
|
|
->get();
|
|
|
|
|
|
// dd($results);
|
|
|
|
$groupedEquipments = [];
|
|
|
|
foreach ($results as $result) {
|
|
if (!isset($groupedEquipments[$result->tag])) {
|
|
$groupedEquipments[$result->tag] = [];
|
|
}
|
|
|
|
$groupedEquipments[$result->tag][] = [
|
|
'description' => $result->description,
|
|
'value' => $result->value
|
|
];
|
|
}
|
|
|
|
$equipments = DB::table('equipments')->get();
|
|
|
|
foreach ($equipments as $equipment) {
|
|
if (isset($groupedEquipments[$equipment->tag])) {
|
|
$equipment->specific_attributes = $groupedEquipments[$equipment->tag];
|
|
}
|
|
}
|
|
$allPossibleAttributes = GeneralAttributesEquipment::all()->pluck('description')->toArray();
|
|
|
|
return view('articulated_2', ['equipments' => $equipments, 'allAttributes' => $allPossibleAttributes]);
|
|
// Retorne a view com os dados
|
|
// return view('test', ['equipments' => $equipments]);
|
|
}
|
|
|
|
|
|
public function listCompanies()
|
|
{
|
|
$companies = User::where('type_users', 3)->get();
|
|
return view('projectsClients/createProject', ['companies' => $companies]);
|
|
}
|
|
|
|
|
|
public function createProject(Request $request)
|
|
{
|
|
|
|
// Validação...
|
|
$installationId = $request->input('installation_id');
|
|
|
|
if ($installationId == 'new_install') {
|
|
// Criar uma nova instalação...
|
|
$newInstallation = new Unit;
|
|
$newInstallation->installation_name = $request->input('new_company_name');
|
|
$newInstallation->address = $request->input('new_company_address');
|
|
$newInstallation->user_id = $request->input('user_id');
|
|
|
|
$newInstallation->save();
|
|
|
|
// Use o id da nova instalação.
|
|
$installationId = $newInstallation->id;
|
|
// dd($installationId);
|
|
}
|
|
|
|
$project = new CompanyProject;
|
|
|
|
$project->description_project = $request->input('description_project');
|
|
$project->n_project_ispt = $request->input('n_project_ispt');
|
|
$project->responsible_project_ispt = $request->input('responsible_project_ispt');
|
|
$project->responsible_project_company = $request->input('responsible_project_company');
|
|
$project->date_started = $request->input('date_started');
|
|
|
|
$project->installation_id = $installationId;
|
|
|
|
$project->save();
|
|
|
|
return redirect()->route('createProject')->with('success', 'Dados guardados com sucesso');
|
|
// return redirect()->route('createProject')->with('success', 'Dados guardados com sucesso');
|
|
|
|
}
|
|
|
|
public function storeProject(Request $request)
|
|
{
|
|
if ($request->input('company_id') == 'new') {
|
|
$company = new CompanyProject; // Substitua "Company" pelo nome do seu modelo de empresas
|
|
$company->name = $request->input('new_company_name');
|
|
$company->save();
|
|
|
|
$company_id = $company->id;
|
|
} else {
|
|
$company_id = $request->input('company_id');
|
|
}
|
|
|
|
// Agora, você pode usar $company_id ao criar o projeto
|
|
}
|
|
|
|
public function getByUserNif(Request $request)
|
|
{
|
|
|
|
// dd(Plant::where('user_id', $request->input('user_id'))->get());
|
|
|
|
$user_id = $request->input('user_id'); //Check
|
|
$installations = Plant::where('user_id', $user_id)->get();
|
|
|
|
return response()->json($installations);
|
|
}
|
|
|
|
public function getAmbits($equipmentType)
|
|
{
|
|
|
|
$ambits = DB::table('ambits_equipments')
|
|
->select('ambits_equipments.*')
|
|
->where('ambits_equipments.equipment_type_id', $equipmentType)
|
|
->get();
|
|
return response()->json($ambits);
|
|
}
|
|
|
|
public function getAttributes($id)
|
|
{
|
|
$equipment = Equipment::with('specificAttributes')->find($id);
|
|
return response()->json($equipment->specificAttributes);
|
|
}
|
|
|
|
// public function createEquipamentProject(Request $request)
|
|
// {
|
|
// $file = $request->file('documento');
|
|
|
|
// // Certifique-se de que um arquivo foi enviado
|
|
// if ($file) {
|
|
// // Carregue o arquivo Excel
|
|
// $spreadsheet = IOFactory::load($file->path());
|
|
|
|
// // Obtenha a primeira planilha
|
|
// $worksheet = $spreadsheet->getSheet(0);
|
|
|
|
// // Transforme os dados da planilha em um array
|
|
// $data = $worksheet->toArray();
|
|
|
|
// $nomesColunas = $data[0];
|
|
|
|
// $dadosLinha6 = $data[6];
|
|
|
|
// $juntarArrays = array_combine($nomesColunas, $dadosLinha6);
|
|
|
|
// $datas = array_filter($juntarArrays, function ($chave) {
|
|
// return !empty($chave);
|
|
// }, ARRAY_FILTER_USE_KEY);
|
|
|
|
// $equipamentType = equipament_type::where('equipment_type_name', $datas['tipo_equipamento'])->first();
|
|
// $checkFactory = factorie::where('factories_name', $datas['fabrica'])->first();
|
|
|
|
|
|
// $newEquipament = new equipament;
|
|
// //Primeiro tem de derificar se a fabrica existe, senão cria uma.
|
|
// $newEquipament->factory_id = $checkFactory->factories_id;
|
|
// $newEquipament->equipament_type_id = $equipamentType->equipament_type_id;
|
|
// $newEquipament->equipment_Description = $datas['equipment_Description'];
|
|
// $newEquipament->tag = $datas['tag'];
|
|
// $newEquipament->serial_number = $datas['n_serie'];
|
|
// $newEquipament->model = $datas['modelo'];
|
|
|
|
// $newEquipament->save();
|
|
|
|
|
|
// $receveEquipment_ID = $newEquipament->id;
|
|
// $receveEquipament_type_ID = $newEquipament->equipament_type_id;
|
|
|
|
|
|
// // Atributos que você quer buscar e inserir
|
|
// $attributes = ["dimension", "dn_ent", "p&id", "n_sap", "isolation", "scaffolding", "grua", "interlocks"];
|
|
|
|
// // $attributes = array_slice($data[0], 7);
|
|
|
|
// foreach ($attributes as $attribute) {
|
|
|
|
// // Buscar o atributo na tabela general_attributes_equipament
|
|
// $generalAttribute = general_attributes_equipament::where('description', $attribute)->first();
|
|
|
|
|
|
// // Se o atributo foi encontrado
|
|
// if (!is_null($generalAttribute)) {
|
|
// // Criar um novo registro em specific_attributes_equipament_Types
|
|
// $specificAttribute = new specific_attributes_equipament_type;
|
|
|
|
// $specificAttribute->tb_equipament_id = $receveEquipment_ID;
|
|
// $specificAttribute->equipament_Type_id = $receveEquipament_type_ID;
|
|
// $specificAttribute->specific_attributes_equipment_type_id = $generalAttribute->general_attributes_equipment_id;
|
|
// $specificAttribute->value = $datas[$attribute];
|
|
|
|
// $specificAttribute->save();
|
|
// }
|
|
// }
|
|
// $listValves = equipament::all();
|
|
|
|
// return redirect()->route('testExcel')->with('success', 'Dados guardados com sucesso')->with('listValves', $listValves);
|
|
// }
|
|
// }
|
|
|
|
|
|
|
|
|
|
// public function createEquipamentProject(Request $request)
|
|
// {
|
|
// $file = $request->file('documento');
|
|
|
|
// // Certifique-se de que um arquivo foi enviado
|
|
// if ($file) {
|
|
// // Carregue o arquivo Excel
|
|
// $spreadsheet = IOFactory::load($file->path());
|
|
|
|
// // Obtenha a primeira planilha
|
|
// $worksheet = $spreadsheet->getSheet(0);
|
|
|
|
// // Transforme os dados da planilha em um array
|
|
// $data = $worksheet->toArray();
|
|
|
|
// $nomesColunas = $data[0];
|
|
|
|
// // Atributos que você quer buscar e inserir
|
|
// $attributes = ["dimension", "dn_ent", "p&id", "n_sap", "isolation", "scaffolding", "grua", "interlocks"];
|
|
|
|
// // Comece a partir da sexta linha
|
|
// for ($i = 6; $i < count($data); $i++) {
|
|
|
|
// $dadosLinha = $data[$i];
|
|
|
|
// //Se não preencher o campo $dadosLinha[0], não cria um novo equipamento
|
|
// //Trocar pelos 5 primeiros
|
|
// if (empty($dadosLinha[0])) {
|
|
// continue;
|
|
// }
|
|
|
|
|
|
// $juntarArrays = array_combine($nomesColunas, $dadosLinha);
|
|
|
|
// $datas = array_filter($juntarArrays, function ($chave) {
|
|
// return !empty($chave);
|
|
// }, ARRAY_FILTER_USE_KEY);
|
|
|
|
// $equipmentType = EquipmentType::where('equipment_type_name', $datas['tipo_equipamento'])->first();
|
|
|
|
// $checkFactory = Unit::where('unit_name', $datas['fabrica'])->first();
|
|
|
|
|
|
// // Antes de criar o novo equipamento, verifique se já existe um equipamento
|
|
// // com o mesmo factory_id e tag.
|
|
// $existingEquipment = Equipment::where('unit_id', $checkFactory->unit_id)
|
|
// ->where('equipment_tag', $datas['tag'])
|
|
// ->first();
|
|
|
|
// if ($existingEquipment) {
|
|
// // Se o equipamento existir, crie o novo equipamento na tabela pending_equipaments.
|
|
// $pendingEquipament = new PendingEquipment;
|
|
// // Defina os atributos do pendingEquipament conforme necessário.
|
|
// $pendingEquipament->pending_equipment_unit_id = $checkFactory->unit_id;
|
|
// $pendingEquipament->pending_equipment_type_id = $equipmentType->equipment_type_id;
|
|
// $pendingEquipament->pending_equipment_tag = $datas['tag'];
|
|
// $pendingEquipament->pending_equipment_description = $datas['equipment_Description'];
|
|
// $pendingEquipament->pending_equipment_serial_number = $datas['n_serie'];
|
|
// $pendingEquipament->pending_equipment_brand = $datas['modelo'];
|
|
|
|
// $pendingEquipament->save();
|
|
|
|
// // Adicione uma variável de sessão para indicar que um equipamento pendente foi criado.
|
|
// session(['pendingEquipmentCreated' => true]);
|
|
|
|
// // Adicione uma variável de sessão para indicar que um equipamento pendente foi criado.
|
|
// session()->push('pendingEquipments', $pendingEquipament);
|
|
|
|
// // Continue com o próximo loop.
|
|
// continue;
|
|
// }
|
|
|
|
// $newEquipament = new Equipment;
|
|
|
|
// $newEquipament->unit_id = $checkFactory->unit_id;
|
|
// $newEquipament->equipment_type_id = $equipmentType->equipment_type_id;
|
|
// $newEquipament->equipment_Description = $datas['equipment_Description'];
|
|
// $newEquipament->equipment_tag = $datas['tag'];
|
|
// $newEquipament->equipment_serial_number = $datas['n_serie'];
|
|
// $newEquipament->equipment_model = $datas['modelo'];
|
|
|
|
// $newEquipament->save();
|
|
|
|
// $receveEquipment_ID = $newEquipament->equipment_id;
|
|
|
|
// $receveEquipament_type_ID = $newEquipament->equipment_type_id;
|
|
|
|
|
|
// foreach ($attributes as $attribute) {
|
|
|
|
// $generalAttribute = GeneralAttributesEquipment::where('general_attributes_equipment_description', $attribute)->first();
|
|
|
|
// if (!is_null($generalAttribute)) {
|
|
|
|
// $specificAttribute = new SpecificAttributesEquipmentType;
|
|
|
|
// $specificAttribute->equipment_id = $receveEquipment_ID;
|
|
// $specificAttribute->equipment_type_id = $receveEquipament_type_ID;
|
|
// $specificAttribute->specific_attributes_equipment_type_id = $generalAttribute->general_attributes_equipment_id;
|
|
// $specificAttribute->specific_attributes_value = $datas[$attribute];
|
|
|
|
// // $specificAttribute->save();
|
|
// }
|
|
// }
|
|
// }
|
|
|
|
// $listValves = Equipment::all();
|
|
// $pendingEquipments = PendingEquipment::all();
|
|
|
|
// // return redirect()->route('createProject')->with('success', 'Dados guardados com sucesso')->with('listValves', $listValves);
|
|
|
|
// // return redirect()->route('createProject')->with('success', 'Dados guardados com sucesso')->with('listValves', $listValves)->with('pendingEquipments', $pendingEquipments);
|
|
|
|
// $listValves = Equipment::all();
|
|
// $pendingEquipments = session('pendingEquipments');
|
|
// if ($pendingEquipments) {
|
|
// return redirect()->route('createProject')->with('success', 'Dados guardados com sucesso')->with('listValves', $listValves)->with('pendingEquipments', $pendingEquipments);
|
|
// } else {
|
|
// return redirect()->route('createProject')->with('success', 'Dados guardados com sucesso')->with('listValves', $listValves);
|
|
// }
|
|
// }
|
|
// }
|
|
}
|