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) => '' . e($value) . '') ->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) => '' . count($row->fields ?? []) . '') ->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); } }