803 lines
36 KiB
PHP
803 lines
36 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Controllers;
|
|
|
|
use Illuminate\Http\Request;
|
|
use Illuminate\Support\Facades\DB;
|
|
use PhpOffice\PhpSpreadsheet\IOFactory;
|
|
|
|
|
|
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;
|
|
|
|
|
|
class CreateProjectController extends Controller
|
|
{
|
|
// 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 nao vai ficar step 1
|
|
return view('projectsClients/createProject', ['step' => 1], ['companies' => $companies]);
|
|
}
|
|
// Progress Bar
|
|
//Devolve para a primeira para na descricao 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 = 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');
|
|
$project->date_started = $request->input('date_started');
|
|
|
|
$project->plant_id = $installationId;
|
|
|
|
$project->save();
|
|
|
|
session(['form_data.step1' => $request->all()]);
|
|
|
|
// // Redirecione o usuário para a próxima etapa
|
|
// return redirect('/test2')
|
|
// ->with('project', $project)
|
|
// ->with('success', 'Dados guardados com sucesso');
|
|
return redirect()->route('test2', ['id' => $project->company_projects_id])
|
|
->with('success', 'Detalhes, Projecto criado com sucesso');
|
|
}
|
|
|
|
public function showStep2($company_projects_id)
|
|
{
|
|
// Verifique se a etapa 1 foi concluída
|
|
|
|
// if (!session('form_data.step1')) {
|
|
// return redirect('/createProject');
|
|
// }
|
|
|
|
//recebe o Id de Plant vai devolver todos os equipamentos relacionados a esta instalacao(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 instalacao
|
|
$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 Ambito para se realizar a tarefas pretendida neste obra.
|
|
// $listEquipmentsProjects = Equipment::with(['unit', 'equipmentType', 'equipmentAssociationAmbit.ambitsEquipment'])
|
|
// ->where('company_projects_id', $company_projects_id)
|
|
// ->get();
|
|
$listEquipmentsProjects = Equipment::with(['unit', 'equipmentType', 'equipmentAssociationAmbit.ambitsEquipment', 'specificAttributes' => function ($query) {
|
|
$query->orderBy('specific_attributes_value', 'asc');
|
|
}])
|
|
->where('company_projects_id', $company_projects_id)
|
|
->get();
|
|
|
|
$pendingEquipments = PendingEquipment::where('pending_company_projects_id', $numberProject)->get();
|
|
|
|
if (!$pendingEquipments->isEmpty()) {
|
|
// Retornamos para a view 'step' => 2 indicando conclusao da primeira parte, $numberProject para associacao de equipamentos a esta obra, alem de todos os equipamentos e fabricao ja existente com base na instalacao 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);
|
|
}
|
|
return view('projectsClients/articulated_2', ['step' => 2, 'numberProject' => $numberProject])
|
|
->with('listEquipmentsProjects', $listEquipmentsProjects)
|
|
->with('typeEquipments', $typeEquipments)
|
|
->with('checkEquipments', $checkEquipments)
|
|
->with('checkUnits', $checkUnits);
|
|
}
|
|
|
|
public function createEquipmentManual(Request $request)
|
|
{
|
|
// EquipmentAmbit
|
|
// *** Recebe a Instalacao(Plant), com base no numero da Obra Criada
|
|
$receivePlant = DB::table('plants')
|
|
->join('company_projects', 'company_projects.plant_id', 'plants.plant_id')
|
|
->select('plants.plant_id')
|
|
->where('company_projects.company_projects_id', '=', $request->numberProject)
|
|
->get();
|
|
|
|
//recebe a lista de todos os equipmentos relacionados a obra que se esta a criar.
|
|
$listEquipmentsProjects = DB::table('equipments')
|
|
->select('equipments.*')
|
|
->where('equipments.company_projects_id', '=', $request->numberProject)
|
|
->get();
|
|
|
|
// Verifica se ja existe um equipamento com as as caracteristicas : tag,unit_id, iguais ao que pretendemos criar
|
|
$existingEquipment = Equipment::firstWhere([
|
|
'equipment_tag' => $request->tag,
|
|
'unit_id' => $request->unit_id
|
|
]);
|
|
|
|
if ($existingEquipment) {
|
|
return redirect()->route('test2', ['id' => $request->numberProject])
|
|
->with('danger', 'Equipamento ja Existe !!')
|
|
->with('listEquipmentsProjects', $listEquipmentsProjects);
|
|
}
|
|
|
|
// Se realmente for um equipamento novo, verifica se ira associar a uma fabrica (unit) nova ou ja existente
|
|
$newEquipmentProject = new Equipment;
|
|
|
|
// Se for uma fabrica(Unit) existente
|
|
if ($request->new_unit_name == null) {
|
|
$newEquipmentProject->unit_id = $request->unit_id;
|
|
} else {
|
|
|
|
//ja retorna se for uma fabrica nova (Unit)
|
|
$newUnit = new Unit;
|
|
$newUnit->unit_name = $request->new_unit_name;
|
|
$newUnit->plant_id = $receivePlant[0]->plant_id;
|
|
$newUnit->save();
|
|
|
|
$newEquipmentProject->unit_id = $newUnit->unit_id;
|
|
}
|
|
$newEquipmentProject->equipment_type_id = $request->equipmentTypeId;
|
|
$newEquipmentProject->equipment_tag = $request->tag;
|
|
$newEquipmentProject->equipment_description = $request->equipmentDescription;
|
|
|
|
// Estes campos a baixo : podem ter valor ou nao
|
|
$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;
|
|
|
|
|
|
|
|
// 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->specific_attributes_equipment_type_id = $receivesAssociationAttribute['general_attributes_equipment_id'];
|
|
$AddAtributsEquipments->specific_attributes_value = $receivesAssociationAttribute['value'];
|
|
$AddAtributsEquipments->save();
|
|
}
|
|
//Criar associacao do equipamento ao Ambito
|
|
$AssociationEquipmentAmbit = new EquipmentAssociationAmbit;
|
|
$AssociationEquipmentAmbit->equipment_type_id = $request->equipmentTypeId;
|
|
$AssociationEquipmentAmbit->ambits_id = $request->EquipmentAmbit;
|
|
$AssociationEquipmentAmbit->equipment_id = $equipmentID;
|
|
$AssociationEquipmentAmbit->save();
|
|
|
|
|
|
// O $request->numberProject e sempre necessario retornar para indicar a obra que se esta modificando...
|
|
return redirect()->route('test2', ['id' => $request->numberProject])
|
|
->with('success', 'Equipamento criado com sucesso')
|
|
->with('listEquipmentsProjects', $listEquipmentsProjects);
|
|
}
|
|
public function receiveIdEquipment(Equipment $equipment){
|
|
// return response()->json($equipment);
|
|
return view('projectsClients/articulated_2', ['equipment' => $equipment]);
|
|
}
|
|
|
|
public function processStep2(Request $request)
|
|
{
|
|
// Valide e processe os dados do formulário
|
|
$file = $request->file('documento');
|
|
|
|
// Recebe a id do Projecto criado
|
|
$company_projects_id = $request->numberProject;
|
|
|
|
// 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 a tabela : general_attributes_equipaments
|
|
$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];
|
|
|
|
$countPendingEquipments = 0;
|
|
$countNewEquipment = 0;
|
|
|
|
// Comece a partir da sexta linha
|
|
for ($i = 6; $i < count($data); $i++) {
|
|
|
|
$dadosLinha = $data[$i];
|
|
|
|
// Verifica se os 5 primeiros campos essenciais estao preenchidos, um deles nao estiver preenchido ele ignora e nao cria o equipamento
|
|
$isEmpty = false;
|
|
for ($j = 0; $j < 5; $j++) {
|
|
if (empty($dadosLinha[$j])) {
|
|
$isEmpty = true;
|
|
break;
|
|
}
|
|
}
|
|
if ($isEmpty) {
|
|
continue;
|
|
}
|
|
|
|
// 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['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->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['tag'];
|
|
$newEquipament->equipment_serial_number = $datas['n_serie'];
|
|
$newEquipament->equipment_model = $datas['modelo'];
|
|
$newEquipament->company_projects_id = $company_projects_id;
|
|
|
|
$newEquipament->save();
|
|
|
|
$countNewEquipment++;
|
|
|
|
// 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['ambito'])->first();
|
|
|
|
if ($ambit) {
|
|
$ambit_id = $ambit->ambits_id;
|
|
}
|
|
|
|
$AssociationEquipmentAmbit = new EquipmentAssociationAmbit;
|
|
|
|
$AssociationEquipmentAmbit->equipment_type_id = $receveEquipament_type_ID;
|
|
$AssociationEquipmentAmbit->ambits_id = $ambit_id;
|
|
$AssociationEquipmentAmbit->equipment_id = $receveEquipment_ID;
|
|
$AssociationEquipmentAmbit->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->specific_attributes_equipment_type_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();
|
|
}
|
|
}
|
|
}
|
|
|
|
$pendingEquipments = PendingEquipment::where('pending_company_projects_id', $request->numberProject)->get();
|
|
|
|
// $pendingEquipments = session('pendingEquipments');
|
|
if ($countPendingEquipments != 0) {
|
|
// return redirect()->route('test2')->with('Danger', 'Equipamentos Pendentes')->with('listValves', $listValves)->with('pendingEquipments', $pendingEquipments);
|
|
return redirect()->route('test2', ['id' => $request->numberProject])
|
|
->with('danger', 'Equipamentos Pendentes criados : ' . $countPendingEquipments)
|
|
->with('pendingEquipments', $pendingEquipments);
|
|
// ->with('success', 'Equipamentos Criados :' . count($listValves))
|
|
}
|
|
return redirect()->route('test2', ['id' => $request->numberProject])
|
|
->with('success', 'Equipamentos Criados :' . $countNewEquipment);
|
|
}
|
|
|
|
//Nao chega aqui ainda pois volta para a pagina com dados ja carregados.
|
|
|
|
session(['form_data.step2' => $request->all()]);
|
|
|
|
// Redirecione o usuário para a próxima etapa
|
|
return redirect('/test3');
|
|
}
|
|
|
|
public function showStep3()
|
|
{
|
|
// Verifique se a etapa 2 foi concluída
|
|
// if (!session('form_data.step2')) {
|
|
// return redirect('/test2');
|
|
// }
|
|
|
|
return view('projectsClients/workStation_3', ['step' => 3]);
|
|
}
|
|
|
|
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 usuário para uma página de "Obrigado" ou processar os dados do formulário
|
|
// ...
|
|
}
|
|
|
|
public function index()
|
|
{
|
|
// $results = DB::table('equipaments')
|
|
// ->join('specific_attributes_equipament_types', 'equipaments.equipment_ID', '=', 'specific_attributes_equipament_types.tb_equipament_id')
|
|
// ->join('general_attributes_equipaments', 'specific_attributes_equipament_types.specific_Attributes_Equipment_Type_ID', '=', 'general_attributes_equipaments.general_Attributes_Equipment_ID')
|
|
// ->select('equipaments.tag', 'general_attributes_equipaments.description', 'specific_attributes_equipament_types.value')
|
|
// ->get();
|
|
|
|
$results = DB::table('equipments')
|
|
->join('specific_attributes_equipament_types', 'equipments.equipment_id', '=', 'specific_attributes_equipament_types.equipment_id')
|
|
->join('general_attributes_equipaments', 'specific_attributes_equipament_types.specific_attributes_equipment_type_id', '=', 'general_attributes_equipaments.general_attributes_equipment_id')
|
|
->select('equipments.equipment_tag', 'general_attributes_equipaments.general_attributes_equipment_description', 'specific_attributes_equipament_types.specific_attributes_value')
|
|
->get();
|
|
|
|
|
|
// dd($results);
|
|
|
|
$groupedEquipments = [];
|
|
|
|
foreach ($results as $result) {
|
|
if (!isset($groupedEquipments[$result->tag])) {
|
|
$groupedEquipments[$result->tag] = [];
|
|
}
|
|
|
|
$groupedEquipments[$result->tag][] = [
|
|
'description' => $result->description,
|
|
'value' => $result->value
|
|
];
|
|
}
|
|
|
|
$equipments = DB::table('equipments')->get();
|
|
|
|
foreach ($equipments as $equipment) {
|
|
if (isset($groupedEquipments[$equipment->tag])) {
|
|
$equipment->specific_attributes = $groupedEquipments[$equipment->tag];
|
|
}
|
|
}
|
|
$allPossibleAttributes = GeneralAttributesEquipment::all()->pluck('description')->toArray();
|
|
|
|
return view('test2', ['equipments' => $equipments, 'allAttributes' => $allPossibleAttributes]);
|
|
// Retorne a view com os dados
|
|
// return view('test', ['equipments' => $equipments]);
|
|
}
|
|
|
|
|
|
public function listCompanies()
|
|
{
|
|
$companies = User::where('type_users', 3)->get();
|
|
return view('projectsClients/createProject', ['companies' => $companies]);
|
|
}
|
|
|
|
|
|
public function createProject(Request $request)
|
|
{
|
|
|
|
// Validação...
|
|
$installationId = $request->input('installation_id');
|
|
|
|
if ($installationId == 'new_install') {
|
|
// Criar uma nova instalação...
|
|
$newInstallation = new Unit;
|
|
$newInstallation->installation_name = $request->input('new_company_name');
|
|
$newInstallation->address = $request->input('new_company_address');
|
|
$newInstallation->user_id = $request->input('user_id');
|
|
|
|
$newInstallation->save();
|
|
|
|
// Use o id da nova instalação.
|
|
$installationId = $newInstallation->id;
|
|
// dd($installationId);
|
|
}
|
|
|
|
$project = new CompanyProject;
|
|
|
|
$project->description_project = $request->input('description_project');
|
|
$project->n_project_ispt = $request->input('n_project_ispt');
|
|
$project->responsible_project_ispt = $request->input('responsible_project_ispt');
|
|
$project->responsible_project_company = $request->input('responsible_project_company');
|
|
$project->date_started = $request->input('date_started');
|
|
|
|
$project->installation_id = $installationId;
|
|
|
|
$project->save();
|
|
|
|
return redirect()->route('createProject')->with('success', 'Dados guardados com sucesso');
|
|
// return redirect()->route('createProject')->with('success', 'Dados guardados com sucesso');
|
|
|
|
}
|
|
|
|
public function storeProject(Request $request)
|
|
{
|
|
if ($request->input('company_id') == 'new') {
|
|
$company = new CompanyProject; // Substitua "Company" pelo nome do seu modelo de empresas
|
|
$company->name = $request->input('new_company_name');
|
|
$company->save();
|
|
|
|
$company_id = $company->id;
|
|
} else {
|
|
$company_id = $request->input('company_id');
|
|
}
|
|
|
|
// Agora, você pode usar $company_id ao criar o projeto
|
|
}
|
|
|
|
public function getByUserNif(Request $request)
|
|
{
|
|
|
|
// dd(Plant::where('user_id', $request->input('user_id'))->get());
|
|
|
|
$user_id = $request->input('user_id'); //Check
|
|
$installations = Plant::where('user_id', $user_id)->get();
|
|
|
|
return response()->json($installations);
|
|
}
|
|
|
|
public function getAmbits($equipmentType)
|
|
{
|
|
|
|
$ambits = DB::table('ambits_equipments')
|
|
->select('ambits_equipments.*')
|
|
->where('ambits_equipments.equipment_type_id', $equipmentType)
|
|
->get();
|
|
return response()->json($ambits);
|
|
}
|
|
|
|
// public function 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, senao 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 nao preencher o campo $dadosLinha[0], nao 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);
|
|
// }
|
|
// }
|
|
// }
|
|
}
|