refactor(templates): plantillas globales + asignación por proyecto (pivot)
- Migración: tabla pivot inspection_template_project; drop de phase_id (asociación a fase descartada); project_id se mantiene en inspection_templates por compat. Migra automáticamente las plantillas existentes (project_id → pivot). - Modelos: Project::inspectionTemplates() ↔ InspectionTemplate::projects() (BTM); retirada la relación phase() de InspectionTemplate. - GlobalTemplateManager (nuevo, ruta /inspection-templates, permiso manage templates): catálogo único global, CRUD + import CSV; sin asociación a fase ni a proyecto. - ProjectTemplatesPicker (nuevo, ruta projects.templates, permiso edit projects): lista global con checkbox para asignar/desasignar plantillas al proyecto. - ProjectMap: el selector de plantillas del mapa lee SOLO las asignadas al proyecto vía pivot. API móvil (bundle + /templates) adaptado al pivot. - Eliminado el viejo TemplateManager por-proyecto, su vista wrapper y la tabla ImportTemplatesTable (ya no aplica: todas son globales). - Acceso "Plantillas" añadido al menú principal (gate manage templates). Tests: GlobalTemplatesTest (4). Suite 89 passing. Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
This commit is contained in:
+40
-142
@@ -2,31 +2,25 @@
|
||||
|
||||
namespace App\Livewire\Inspections;
|
||||
|
||||
use Livewire\Component;
|
||||
use Livewire\Attributes\On;
|
||||
use Livewire\WithFileUploads;
|
||||
use App\Models\InspectionTemplate;
|
||||
use App\Models\Project;
|
||||
use App\Models\Phase;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Livewire\Attributes\Layout;
|
||||
use Livewire\Component;
|
||||
use Livewire\WithFileUploads;
|
||||
use PhpOffice\PhpSpreadsheet\IOFactory;
|
||||
|
||||
class TemplateManager extends Component
|
||||
#[Layout('layouts.app')]
|
||||
class GlobalTemplateManager extends Component
|
||||
{
|
||||
use WithFileUploads;
|
||||
|
||||
public $project;
|
||||
public $templates;
|
||||
public $phases;
|
||||
|
||||
// ── Formulario principal ───────────────────────────────────────────────
|
||||
public $editingTemplate = null;
|
||||
public $showForm = false;
|
||||
public $form = [
|
||||
'name' => '',
|
||||
'description' => '',
|
||||
'phase_id' => null,
|
||||
'is_global' => false,
|
||||
'fields' => [],
|
||||
];
|
||||
|
||||
@@ -37,9 +31,6 @@ class TemplateManager extends Component
|
||||
public $importTemplateName = '';
|
||||
public $importError = '';
|
||||
|
||||
// ── Importar desde otro proyecto (tabla Rappasoft) ─────────────────────
|
||||
public $showImportProjectModal = false;
|
||||
|
||||
public $fieldTypes = [
|
||||
'text' => 'Texto corto',
|
||||
'textarea' => 'Texto largo',
|
||||
@@ -51,31 +42,18 @@ class TemplateManager extends Component
|
||||
'select' => 'Lista desplegable',
|
||||
];
|
||||
|
||||
public function mount(Project $project)
|
||||
public function mount()
|
||||
{
|
||||
$this->project = $project;
|
||||
$this->loadPhases();
|
||||
abort_unless(Auth::user()->can('manage templates'), 403);
|
||||
$this->loadTemplates();
|
||||
}
|
||||
|
||||
public function loadPhases()
|
||||
{
|
||||
$this->phases = $this->project->phases()->orderBy('name')->get();
|
||||
}
|
||||
|
||||
public function loadTemplates()
|
||||
{
|
||||
// Plantillas del proyecto + globales (project_id null)
|
||||
$this->templates = InspectionTemplate::where(function ($q) {
|
||||
$q->where('project_id', $this->project->id)->orWhereNull('project_id');
|
||||
})
|
||||
->with('phase')
|
||||
->orderBy('name')
|
||||
->get();
|
||||
// Catálogo global: todas las plantillas.
|
||||
$this->templates = InspectionTemplate::orderBy('name')->get();
|
||||
}
|
||||
|
||||
// ── Formulario manual ─────────────────────────────────────────────────
|
||||
|
||||
public function newTemplate()
|
||||
{
|
||||
$this->resetForm();
|
||||
@@ -88,8 +66,6 @@ class TemplateManager extends Component
|
||||
$this->form = [
|
||||
'name' => $template->name,
|
||||
'description' => $template->description ?? '',
|
||||
'phase_id' => $template->phase_id,
|
||||
'is_global' => is_null($template->project_id),
|
||||
'fields' => $template->fields ?? [],
|
||||
];
|
||||
$this->editingTemplate = $id;
|
||||
@@ -107,8 +83,6 @@ class TemplateManager extends Component
|
||||
$this->form = [
|
||||
'name' => '',
|
||||
'description' => '',
|
||||
'phase_id' => null,
|
||||
'is_global' => false,
|
||||
'fields' => [],
|
||||
];
|
||||
$this->editingTemplate = null;
|
||||
@@ -140,25 +114,23 @@ class TemplateManager extends Component
|
||||
public function saveTemplate()
|
||||
{
|
||||
$this->validate([
|
||||
'form.name' => 'required|string|max:255',
|
||||
'form.phase_id' => 'nullable|exists:phases,id',
|
||||
'form.fields' => 'array',
|
||||
'form.name' => 'required|string|max:255',
|
||||
'form.fields' => 'array',
|
||||
]);
|
||||
|
||||
$data = [
|
||||
'name' => $this->form['name'],
|
||||
'description' => $this->form['description'],
|
||||
'project_id' => ($this->form['is_global'] ?? false) ? null : $this->project->id,
|
||||
'phase_id' => ($this->form['is_global'] ?? false) ? null : ($this->form['phase_id'] ?: null),
|
||||
'project_id' => null,
|
||||
'fields' => array_values($this->form['fields']),
|
||||
];
|
||||
|
||||
if ($this->editingTemplate) {
|
||||
InspectionTemplate::findOrFail($this->editingTemplate)->update($data);
|
||||
$this->dispatch('notify', 'Template actualizado correctamente');
|
||||
$this->dispatch('notify', 'Plantilla actualizada');
|
||||
} else {
|
||||
InspectionTemplate::create($data);
|
||||
$this->dispatch('notify', 'Template creado correctamente');
|
||||
$this->dispatch('notify', 'Plantilla creada');
|
||||
}
|
||||
|
||||
$this->cancelForm();
|
||||
@@ -169,86 +141,35 @@ class TemplateManager extends Component
|
||||
{
|
||||
InspectionTemplate::findOrFail($id)->delete();
|
||||
$this->loadTemplates();
|
||||
$this->dispatch('notify', 'Template eliminado');
|
||||
$this->dispatch('notify', 'Plantilla eliminada');
|
||||
}
|
||||
|
||||
// ── Exportar template a CSV ────────────────────────────────────────────
|
||||
|
||||
public function exportTemplate($id)
|
||||
{
|
||||
$template = InspectionTemplate::findOrFail($id);
|
||||
$rows = [];
|
||||
$rows[] = ['name', 'label', 'type', 'required', 'options', 'min', 'max', 'step'];
|
||||
|
||||
foreach ($template->fields as $field) {
|
||||
$rows[] = [
|
||||
$field['name'] ?? '',
|
||||
$field['label'] ?? '',
|
||||
$field['type'] ?? 'text',
|
||||
($field['required'] ?? false) ? '1' : '0',
|
||||
$field['options'] ?? '',
|
||||
$field['min'] ?? '',
|
||||
$field['max'] ?? '',
|
||||
$field['step'] ?? '',
|
||||
];
|
||||
}
|
||||
|
||||
$filename = preg_replace('/[^a-z0-9_\-]/i', '_', $template->name) . '.csv';
|
||||
|
||||
return response()->streamDownload(function () use ($rows) {
|
||||
$out = fopen('php://output', 'w');
|
||||
// BOM para Excel con UTF-8
|
||||
fwrite($out, "\xEF\xBB\xBF");
|
||||
foreach ($rows as $row) {
|
||||
fputcsv($out, $row);
|
||||
}
|
||||
fclose($out);
|
||||
}, $filename, ['Content-Type' => 'text/csv; charset=UTF-8']);
|
||||
}
|
||||
|
||||
public function downloadExampleCsv()
|
||||
{
|
||||
$rows = [
|
||||
['name', 'label', 'type', 'required', 'options', 'min', 'max', 'step'],
|
||||
['altura_viga', 'Altura de viga (mm)', 'decimal', '1', '', '0', '2000', '1'],
|
||||
['estado_armado', 'Estado del armado', 'select', '1', 'Conforme,No conforme,Obs.', '', '', ''],
|
||||
['fotos_tomadas', '¿Fotos tomadas?', 'boolean', '1', '', '', '', ''],
|
||||
['observaciones', 'Observaciones generales','textarea', '0', '', '', '', ''],
|
||||
['fecha_visita', 'Fecha de visita', 'date', '0', '', '', '', ''],
|
||||
['avance_pct', 'Avance medido (%)', 'percentage', '0', '', '0', '100', '1'],
|
||||
];
|
||||
|
||||
return response()->streamDownload(function () use ($rows) {
|
||||
$out = fopen('php://output', 'w');
|
||||
fwrite($out, "\xEF\xBB\xBF");
|
||||
foreach ($rows as $row) {
|
||||
fputcsv($out, $row);
|
||||
}
|
||||
fclose($out);
|
||||
}, 'ejemplo-template.csv', ['Content-Type' => 'text/csv; charset=UTF-8']);
|
||||
}
|
||||
|
||||
// ── Importar desde CSV / Excel ─────────────────────────────────────────
|
||||
// ── Importar desde CSV/Excel ───────────────────────────────────────────
|
||||
|
||||
public function openImportFileModal()
|
||||
{
|
||||
$this->importFile = null;
|
||||
$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',
|
||||
], [
|
||||
'importFile.required' => 'Selecciona un archivo.',
|
||||
'importFile.mimes' => 'Solo se aceptan archivos CSV o Excel (xlsx/xls).',
|
||||
'importTemplateName.required' => 'Escribe un nombre para el template.',
|
||||
]);
|
||||
|
||||
try {
|
||||
@@ -259,14 +180,11 @@ class TemplateManager extends Component
|
||||
}
|
||||
|
||||
$fields = $this->parseRows($rows);
|
||||
|
||||
if (empty($fields)) {
|
||||
$this->importError = 'No se encontraron filas de datos válidas. Revisa que el archivo tenga el formato correcto.';
|
||||
$this->importError = 'No se encontraron filas válidas.';
|
||||
return;
|
||||
}
|
||||
|
||||
$this->importPreviewFields = $fields;
|
||||
$this->dispatch('notify', count($fields) . ' campos detectados. Revisa la vista previa.');
|
||||
}
|
||||
|
||||
public function confirmImportFile()
|
||||
@@ -276,17 +194,16 @@ class TemplateManager extends Component
|
||||
InspectionTemplate::create([
|
||||
'name' => $this->importTemplateName,
|
||||
'description' => 'Importado desde archivo',
|
||||
'project_id' => $this->project->id,
|
||||
'phase_id' => null,
|
||||
'project_id' => null,
|
||||
'fields' => array_values($this->importPreviewFields),
|
||||
]);
|
||||
|
||||
$this->showImportFileModal = false;
|
||||
$this->importPreviewFields = [];
|
||||
$this->importTemplateName = '';
|
||||
$this->importFile = null;
|
||||
$this->showImportFileModal = false;
|
||||
$this->importPreviewFields = [];
|
||||
$this->importTemplateName = '';
|
||||
$this->importFile = null;
|
||||
$this->loadTemplates();
|
||||
$this->dispatch('notify', 'Template importado correctamente desde archivo');
|
||||
$this->dispatch('notify', 'Plantilla importada');
|
||||
}
|
||||
|
||||
private function readFileRows(): array
|
||||
@@ -298,18 +215,15 @@ class TemplateManager extends Component
|
||||
$spreadsheet = IOFactory::load($path);
|
||||
$sheet = $spreadsheet->getActiveSheet();
|
||||
$rows = $sheet->toArray(null, true, true, false);
|
||||
array_shift($rows); // quitar cabecera
|
||||
return array_filter($rows, fn($r) => !empty($r[0]));
|
||||
array_shift($rows);
|
||||
return array_filter($rows, fn ($r) => !empty($r[0]));
|
||||
}
|
||||
|
||||
// CSV / TXT
|
||||
$rows = [];
|
||||
$handle = fopen($path, 'r');
|
||||
// Detectar y descartar BOM UTF-8
|
||||
$bom = fread($handle, 3);
|
||||
if ($bom !== "\xEF\xBB\xBF") rewind($handle);
|
||||
|
||||
fgetcsv($handle); // cabecera
|
||||
fgetcsv($handle);
|
||||
while (($row = fgetcsv($handle)) !== false) {
|
||||
if (!empty($row[0])) $rows[] = $row;
|
||||
}
|
||||
@@ -331,9 +245,9 @@ class TemplateManager extends Component
|
||||
'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 ? $row[5] : null,
|
||||
'max' => $row[6] !== '' && $row[6] !== null ? $row[6] : null,
|
||||
'step' => $row[7] !== '' && $row[7] !== null ? $row[7] : null,
|
||||
'min' => ($row[5] ?? '') !== '' ? $row[5] : null,
|
||||
'max' => ($row[6] ?? '') !== '' ? $row[6] : null,
|
||||
'step' => ($row[7] ?? '') !== '' ? $row[7] : null,
|
||||
];
|
||||
}
|
||||
return $fields;
|
||||
@@ -362,24 +276,8 @@ class TemplateManager extends Component
|
||||
return $map[strtolower(trim($type))] ?? 'text';
|
||||
}
|
||||
|
||||
// ── Importar desde otro proyecto ──────────────────────────────────────
|
||||
|
||||
public function openImportProjectModal()
|
||||
{
|
||||
$this->showImportProjectModal = true;
|
||||
}
|
||||
|
||||
/** La tabla Rappasoft embebida avisa cuando ha importado plantillas. */
|
||||
#[On('templates-imported')]
|
||||
public function onTemplatesImported(int $count = 0): void
|
||||
{
|
||||
$this->showImportProjectModal = false;
|
||||
$this->loadTemplates();
|
||||
$this->dispatch('notify', "$count plantilla(s) importada(s) desde otro proyecto");
|
||||
}
|
||||
|
||||
public function render()
|
||||
{
|
||||
return view('livewire.inspections.template-manager');
|
||||
return view('livewire.inspections.global-template-manager');
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user