Files
construprogress/app/Livewire/Inspections/GlobalTemplateManager.php
T

290 lines
9.2 KiB
PHP
Raw Normal View History

2026-05-07 23:31:33 +02:00
<?php
namespace App\Livewire\Inspections;
2026-05-07 23:31:33 +02:00
use App\Models\InspectionTemplate;
use Illuminate\Support\Facades\Auth;
use Livewire\Attributes\Layout;
use Livewire\Attributes\On;
use Livewire\Component;
use Livewire\WithFileUploads;
use PhpOffice\PhpSpreadsheet\IOFactory;
2026-05-07 23:31:33 +02:00
#[Layout('layouts.app')]
class GlobalTemplateManager extends Component
2026-05-07 23:31:33 +02:00
{
use WithFileUploads;
2026-05-07 23:31:33 +02:00
public $templates;
2026-05-07 23:31:33 +02:00
public $editingTemplate = null;
public $showForm = false;
2026-05-07 23:31:33 +02:00
public $form = [
'name' => '',
2026-05-07 23:31:33 +02:00
'description' => '',
'fields' => [],
];
// ── Importar desde CSV/Excel ───────────────────────────────────────────
public $showImportFileModal = false;
public $importFile = null;
public $importPreviewFields = [];
public $importTemplateName = '';
public $importError = '';
public $fieldTypes = [
'text' => 'Texto corto',
'textarea' => 'Texto largo',
'integer' => 'Número entero',
'decimal' => 'Número decimal',
'percentage' => 'Porcentaje (0-100)',
'boolean' => 'Sí/No (checkbox)',
'date' => 'Fecha',
'select' => 'Lista desplegable',
];
public function mount()
2026-05-07 23:31:33 +02:00
{
abort_unless(Auth::user()->can('manage templates'), 403);
2026-05-07 23:31:33 +02:00
$this->loadTemplates();
}
public function loadTemplates()
{
// Catálogo global: todas las plantillas.
$this->templates = InspectionTemplate::orderBy('name')->get();
2026-05-07 23:31:33 +02:00
}
public function newTemplate()
{
$this->resetForm();
$this->showForm = true;
}
#[On('template-edit')]
2026-05-07 23:31:33 +02:00
public function editTemplate($id)
{
$template = InspectionTemplate::findOrFail($id);
$this->form = [
'name' => $template->name,
'description' => $template->description ?? '',
'fields' => $template->fields ?? [],
];
2026-05-07 23:31:33 +02:00
$this->editingTemplate = $id;
$this->showForm = true;
}
public function cancelForm()
{
$this->showForm = false;
$this->resetForm();
}
public function resetForm()
{
$this->form = [
'name' => '',
2026-05-07 23:31:33 +02:00
'description' => '',
'fields' => [],
2026-05-07 23:31:33 +02:00
];
$this->editingTemplate = null;
}
public function addField()
{
$this->form['fields'][] = [
'group' => '',
'name' => '',
'label' => '',
'question' => '',
'type' => 'text',
'options' => '',
2026-05-07 23:31:33 +02:00
'required' => false,
'min' => null,
'max' => null,
'step' => null,
'help' => '',
2026-05-07 23:31:33 +02:00
];
}
public function removeField($index)
{
unset($this->form['fields'][$index]);
$this->form['fields'] = array_values($this->form['fields']);
}
public function saveTemplate()
{
$this->validate([
'form.name' => 'required|string|max:255',
'form.fields' => 'array',
2026-05-07 23:31:33 +02:00
]);
$data = [
'name' => $this->form['name'],
'description' => $this->form['description'],
'project_id' => null,
'fields' => array_values($this->form['fields']),
];
2026-05-07 23:31:33 +02:00
if ($this->editingTemplate) {
InspectionTemplate::findOrFail($this->editingTemplate)->update($data);
$this->dispatch('notify', 'Plantilla actualizada');
2026-05-07 23:31:33 +02:00
} else {
InspectionTemplate::create($data);
$this->dispatch('notify', 'Plantilla creada');
2026-05-07 23:31:33 +02:00
}
$this->cancelForm();
$this->loadTemplates();
$this->dispatch('templates-changed');
2026-05-07 23:31:33 +02:00
}
#[On('template-delete')]
2026-05-07 23:31:33 +02:00
public function deleteTemplate($id)
{
InspectionTemplate::findOrFail($id)->delete();
2026-05-07 23:31:33 +02:00
$this->loadTemplates();
$this->dispatch('templates-changed');
$this->dispatch('notify', 'Plantilla eliminada');
}
// ── Importar desde CSV/Excel ───────────────────────────────────────────
public function openImportFileModal()
{
$this->importFile = null;
$this->importPreviewFields = [];
$this->importTemplateName = '';
$this->importError = '';
$this->showImportFileModal = true;
}
public function downloadExampleCsv()
{
$headers = ['Content-Type' => 'text/csv'];
$csv = "name,label,type,required,options,min,max,step\n"
. "altura,Altura (m),decimal,1,,0,100,0.1\n"
. "ok,¿OK?,boolean,1,,,,\n";
return response()->streamDownload(fn () => print($csv), 'plantilla_ejemplo.csv', $headers);
}
public function parseImportFile()
{
$this->importError = '';
$this->validate([
'importFile' => 'required|file|mimes:csv,txt,xlsx,xls|max:5120',
'importTemplateName' => 'required|string|max:255',
]);
try {
$rows = $this->readFileRows();
} catch (\Throwable $e) {
$this->importError = 'No se pudo leer el archivo: ' . $e->getMessage();
return;
}
$fields = $this->parseRows($rows);
if (empty($fields)) {
$this->importError = 'No se encontraron filas válidas.';
return;
}
$this->importPreviewFields = $fields;
}
public function confirmImportFile()
{
if (empty($this->importPreviewFields) || empty($this->importTemplateName)) return;
InspectionTemplate::create([
'name' => $this->importTemplateName,
'description' => 'Importado desde archivo',
'project_id' => null,
'fields' => array_values($this->importPreviewFields),
]);
$this->showImportFileModal = false;
$this->importPreviewFields = [];
$this->importTemplateName = '';
$this->importFile = null;
$this->loadTemplates();
$this->dispatch('templates-changed');
$this->dispatch('notify', 'Plantilla importada');
}
private function readFileRows(): array
{
$ext = strtolower($this->importFile->getClientOriginalExtension());
$path = $this->importFile->getRealPath();
if ($ext === 'xlsx' || $ext === 'xls') {
$spreadsheet = IOFactory::load($path);
$sheet = $spreadsheet->getActiveSheet();
$rows = $sheet->toArray(null, true, true, false);
array_shift($rows);
return array_filter($rows, fn ($r) => !empty($r[0]));
}
$rows = [];
$handle = fopen($path, 'r');
$bom = fread($handle, 3);
if ($bom !== "\xEF\xBB\xBF") rewind($handle);
fgetcsv($handle);
while (($row = fgetcsv($handle)) !== false) {
if (!empty($row[0])) $rows[] = $row;
}
fclose($handle);
return $rows;
}
private function parseRows(array $rows): array
{
$fields = [];
foreach ($rows as $row) {
$row = array_values((array) $row);
$rawName = trim($row[0] ?? '');
if ($rawName === '') continue;
$fields[] = [
'name' => $this->slugify($rawName),
'label' => trim($row[1] ?? $rawName),
'type' => $this->normalizeType($row[2] ?? 'text'),
'required' => in_array(strtolower(trim($row[3] ?? '0')), ['1', 'si', 'sí', 'yes', 'true']),
'options' => trim($row[4] ?? ''),
'min' => ($row[5] ?? '') !== '' ? $row[5] : null,
'max' => ($row[6] ?? '') !== '' ? $row[6] : null,
'step' => ($row[7] ?? '') !== '' ? $row[7] : null,
];
}
return $fields;
}
private function slugify(string $str): string
{
$str = mb_strtolower(trim($str));
$str = preg_replace('/\s+/', '_', $str);
$str = preg_replace('/[^a-z0-9_]/i', '', $str);
return trim($str, '_') ?: 'campo';
}
private function normalizeType(string $type): string
{
$map = [
'texto' => 'text', 'text' => 'text', 'string' => 'text', 'corto' => 'text',
'textarea' => 'textarea', 'largo' => 'textarea', 'parrafo' => 'textarea',
'integer' => 'integer', 'entero' => 'integer', 'int' => 'integer', 'numero' => 'integer',
'decimal' => 'decimal', 'float' => 'decimal', 'number' => 'decimal', 'numerico' => 'decimal',
'percentage' => 'percentage', 'porcentaje' => 'percentage', 'pct' => 'percentage', '%' => 'percentage',
'boolean' => 'boolean', 'bool' => 'boolean', 'checkbox' => 'boolean', 'sino' => 'boolean', 'si/no' => 'boolean',
'date' => 'date', 'fecha' => 'date',
'select' => 'select', 'lista' => 'select', 'dropdown' => 'select', 'opciones' => 'select',
];
return $map[strtolower(trim($type))] ?? 'text';
}
2026-05-07 23:31:33 +02:00
public function render()
{
return view('livewire.inspections.global-template-manager');
2026-05-07 23:31:33 +02:00
}
}