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:
@@ -49,7 +49,8 @@ class ProjectApiController extends Controller
|
||||
$features = $changed(Feature::whereIn('layer_id', $allLayerIds))->get();
|
||||
$inspections = $changed(Inspection::where('project_id', $project->id))->get();
|
||||
$issues = $changed(Issue::where('project_id', $project->id))->get();
|
||||
$templates = $changed(InspectionTemplate::where('project_id', $project->id))->get();
|
||||
// Plantillas asignadas al proyecto (catálogo global vía pivot)
|
||||
$templates = $changed(InspectionTemplate::whereHas('projects', fn ($q) => $q->where('projects.id', $project->id)))->get();
|
||||
|
||||
$allIssueIds = Issue::withTrashed()->where('project_id', $project->id)->pluck('id');
|
||||
$issueTasks = $changed(IssueTask::whereIn('issue_id', $allIssueIds))->get();
|
||||
@@ -92,7 +93,8 @@ class ProjectApiController extends Controller
|
||||
|
||||
$projectIds = Project::accessibleBy($request->user())->pluck('id');
|
||||
|
||||
$query = InspectionTemplate::whereIn('project_id', $projectIds);
|
||||
// Plantillas asignadas a cualquier proyecto al que el usuario tenga acceso
|
||||
$query = InspectionTemplate::whereHas('projects', fn ($q) => $q->whereIn('projects.id', $projectIds));
|
||||
if ($since) {
|
||||
$query->where('updated_at', '>', $since);
|
||||
}
|
||||
|
||||
+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');
|
||||
}
|
||||
}
|
||||
@@ -1,121 +0,0 @@
|
||||
<?php
|
||||
|
||||
namespace App\Livewire\Projects;
|
||||
|
||||
use App\Models\InspectionTemplate;
|
||||
use App\Models\Project;
|
||||
use Illuminate\Database\Eloquent\Builder;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Rappasoft\LaravelLivewireTables\DataTableComponent;
|
||||
use Rappasoft\LaravelLivewireTables\Views\Column;
|
||||
use Rappasoft\LaravelLivewireTables\Views\Filters\SelectFilter;
|
||||
use Rappasoft\LaravelLivewireTables\Views\Filters\TextFilter;
|
||||
|
||||
class ImportTemplatesTable extends DataTableComponent
|
||||
{
|
||||
protected $model = InspectionTemplate::class;
|
||||
|
||||
public int $projectId;
|
||||
|
||||
public function configure(): void
|
||||
{
|
||||
$this->setPrimaryKey('id')
|
||||
->setDefaultSort('inspection_templates.name', 'asc')
|
||||
->setSortingPillsEnabled(false)
|
||||
->setBulkActionsEnabled(true)
|
||||
->setAdditionalSelects([
|
||||
'inspection_templates.id as id',
|
||||
'inspection_templates.project_id as project_id',
|
||||
'inspection_templates.phase_id as phase_id',
|
||||
]);
|
||||
}
|
||||
|
||||
/** Sólo plantillas de proyectos accesibles, distintos del proyecto destino. */
|
||||
private function accessibleProjectIds()
|
||||
{
|
||||
return Project::accessibleBy(Auth::user())->pluck('id');
|
||||
}
|
||||
|
||||
public function builder(): Builder
|
||||
{
|
||||
return InspectionTemplate::query()
|
||||
->whereIn('inspection_templates.project_id', $this->accessibleProjectIds())
|
||||
->where('inspection_templates.project_id', '!=', $this->projectId)
|
||||
->with(['project', 'phase']);
|
||||
}
|
||||
|
||||
public function columns(): array
|
||||
{
|
||||
return [
|
||||
Column::make('Plantilla', 'name')
|
||||
->sortable()->searchable()
|
||||
->secondaryHeaderFilter('name')
|
||||
->format(fn ($value) => '<span class="font-medium">' . e($value) . '</span>')
|
||||
->html(),
|
||||
|
||||
Column::make('Proyecto')
|
||||
->secondaryHeaderFilter('project')
|
||||
->label(fn ($row) => e($row->project?->name ?? '—')),
|
||||
|
||||
Column::make('Fase')
|
||||
->label(fn ($row) => e($row->phase?->name ?? '—')),
|
||||
|
||||
Column::make('Campos')
|
||||
->label(fn ($row) => '<span class="badge badge-ghost badge-sm">' . count($row->fields ?? []) . '</span>')
|
||||
->html(),
|
||||
];
|
||||
}
|
||||
|
||||
public function filters(): array
|
||||
{
|
||||
$projects = Project::whereIn('id', InspectionTemplate::query()
|
||||
->whereIn('project_id', $this->accessibleProjectIds())
|
||||
->where('project_id', '!=', $this->projectId)
|
||||
->distinct()->pluck('project_id'))
|
||||
->orderBy('name')->pluck('name', 'id')->toArray();
|
||||
|
||||
return [
|
||||
TextFilter::make('Plantilla', 'name')
|
||||
->config(['placeholder' => 'Buscar nombre…'])
|
||||
->filter(fn (Builder $q, string $v) => $q->where('inspection_templates.name', 'like', '%' . $v . '%')),
|
||||
|
||||
SelectFilter::make('Proyecto', 'project')
|
||||
->options(['' => 'Todos'] + $projects)
|
||||
->filter(fn (Builder $q, string $v) => $q->where('inspection_templates.project_id', $v)),
|
||||
];
|
||||
}
|
||||
|
||||
public function bulkActions(): array
|
||||
{
|
||||
return ['importSelected' => 'Importar seleccionadas'];
|
||||
}
|
||||
|
||||
public function importSelected()
|
||||
{
|
||||
$allowed = $this->accessibleProjectIds();
|
||||
$imported = 0;
|
||||
|
||||
foreach (InspectionTemplate::whereIn('id', $this->getSelected())->get() as $source) {
|
||||
if (! $allowed->contains($source->project_id) || $source->project_id === $this->projectId) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$name = $source->name;
|
||||
if (InspectionTemplate::where('project_id', $this->projectId)->where('name', $name)->exists()) {
|
||||
$name .= ' (copia)';
|
||||
}
|
||||
|
||||
InspectionTemplate::create([
|
||||
'name' => $name,
|
||||
'description' => $source->description,
|
||||
'project_id' => $this->projectId,
|
||||
'phase_id' => null,
|
||||
'fields' => $source->fields,
|
||||
]);
|
||||
$imported++;
|
||||
}
|
||||
|
||||
$this->clearSelected();
|
||||
$this->dispatch('templates-imported', count: $imported);
|
||||
}
|
||||
}
|
||||
@@ -107,7 +107,10 @@ class ProjectMap extends Component
|
||||
|
||||
public function loadTemplates()
|
||||
{
|
||||
$this->templates = InspectionTemplate::where('project_id', $this->project->id)->get();
|
||||
// Las plantillas son globales; cada proyecto elige cuáles usa (pivot).
|
||||
$this->templates = $this->project->inspectionTemplates()
|
||||
->orderBy('inspection_templates.name')
|
||||
->get();
|
||||
}
|
||||
|
||||
// ─── Layer / Phase visibility ────────────────────────────────────────────────
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
<?php
|
||||
|
||||
namespace App\Livewire\Projects;
|
||||
|
||||
use App\Models\InspectionTemplate;
|
||||
use App\Models\Project;
|
||||
use Illuminate\Support\Facades\Auth;
|
||||
use Livewire\Attributes\Layout;
|
||||
use Livewire\Component;
|
||||
|
||||
#[Layout('layouts.app')]
|
||||
class ProjectTemplatesPicker extends Component
|
||||
{
|
||||
public Project $project;
|
||||
public array $assignedIds = [];
|
||||
public string $search = '';
|
||||
|
||||
public function mount(Project $project)
|
||||
{
|
||||
$this->project = $project;
|
||||
abort_unless(Auth::user()->can('edit projects'), 403);
|
||||
$this->assignedIds = $project->inspectionTemplates()->pluck('inspection_templates.id')->map(fn ($v) => (int) $v)->all();
|
||||
}
|
||||
|
||||
public function toggle(int $templateId): void
|
||||
{
|
||||
abort_unless(Auth::user()->can('edit projects'), 403);
|
||||
InspectionTemplate::findOrFail($templateId); // valida
|
||||
|
||||
if (in_array($templateId, $this->assignedIds, true)) {
|
||||
$this->project->inspectionTemplates()->detach($templateId);
|
||||
$this->assignedIds = array_values(array_diff($this->assignedIds, [$templateId]));
|
||||
$this->dispatch('notify', 'Plantilla desasignada del proyecto');
|
||||
} else {
|
||||
$this->project->inspectionTemplates()->syncWithoutDetaching([$templateId]);
|
||||
$this->assignedIds[] = $templateId;
|
||||
$this->dispatch('notify', 'Plantilla asignada al proyecto');
|
||||
}
|
||||
}
|
||||
|
||||
public function render()
|
||||
{
|
||||
$templates = InspectionTemplate::query()
|
||||
->when($this->search !== '', fn ($q) => $q->where('name', 'like', '%' . $this->search . '%'))
|
||||
->orderBy('name')->get();
|
||||
|
||||
return view('livewire.projects.project-templates-picker', [
|
||||
'templates' => $templates,
|
||||
]);
|
||||
}
|
||||
}
|
||||
@@ -6,22 +6,24 @@ use Illuminate\Database\Eloquent\Model;
|
||||
|
||||
class InspectionTemplate extends Model
|
||||
{
|
||||
protected $fillable = ['name', 'description', 'project_id', 'phase_id', 'fields'];
|
||||
protected $fillable = ['name', 'description', 'project_id', 'fields'];
|
||||
|
||||
protected $casts = ['fields' => 'array'];
|
||||
|
||||
/** Proyecto que la creó (informativo; ya no determina visibilidad). */
|
||||
public function project()
|
||||
{
|
||||
return $this->belongsTo(Project::class);
|
||||
}
|
||||
|
||||
public function phase()
|
||||
/** Proyectos a los que está asignada esta plantilla (pivot). */
|
||||
public function projects()
|
||||
{
|
||||
return $this->belongsTo(Phase::class);
|
||||
return $this->belongsToMany(Project::class, 'inspection_template_project')->withTimestamps();
|
||||
}
|
||||
|
||||
public function inspections()
|
||||
{
|
||||
return $this->hasMany(Inspection::class);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -58,6 +58,12 @@ class Project extends Model
|
||||
return $this->morphMany(Media::class, 'mediable');
|
||||
}
|
||||
|
||||
/** Plantillas de inspección asignadas a este proyecto (catálogo global ↔ pivot). */
|
||||
public function inspectionTemplates()
|
||||
{
|
||||
return $this->belongsToMany(InspectionTemplate::class, 'inspection_template_project')->withTimestamps();
|
||||
}
|
||||
|
||||
public function images()
|
||||
{
|
||||
return $this->morphMany(Media::class, 'mediable')->where('category', 'image');
|
||||
|
||||
Reference in New Issue
Block a user