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:
2026-06-25 17:26:12 +02:00
co-authored by Claude Opus 4.7
parent 7256c87182
commit f8a68312a3
17 changed files with 386 additions and 639 deletions
+4 -4
View File
@@ -273,11 +273,11 @@ class MobileApiTest extends TestCase
{
$user = User::factory()->create();
$project = $this->makeProject($user);
InspectionTemplate::create([
'project_id' => $project->id,
'name' => 'Plantilla A',
'fields' => [['name' => 'ok', 'label' => 'OK', 'type' => 'boolean']],
$tpl = InspectionTemplate::create([
'name' => 'Plantilla A',
'fields' => [['name' => 'ok', 'label' => 'OK', 'type' => 'boolean']],
]);
$project->inspectionTemplates()->attach($tpl->id);
Sanctum::actingAs($user, ['mobile-sync']);
$res = $this->getJson('/api/v1/templates')->assertOk();
+101
View File
@@ -0,0 +1,101 @@
<?php
namespace Tests\Feature;
use App\Livewire\Inspections\GlobalTemplateManager;
use App\Livewire\Projects\ProjectMap;
use App\Livewire\Projects\ProjectTemplatesPicker;
use App\Models\InspectionTemplate;
use App\Models\Layer;
use App\Models\Phase;
use App\Models\Project;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;
use Spatie\Permission\Models\Permission;
use Tests\TestCase;
class GlobalTemplatesTest extends TestCase
{
use RefreshDatabase;
private function project(User $owner, string $ref = 'P'): Project
{
$p = Project::create([
'reference' => $ref, 'name' => 'P-' . $ref, 'address' => 'x', 'lat' => 40, 'lng' => -3,
'start_date' => now()->toDateString(), 'end_date_estimated' => now()->addMonth()->toDateString(),
'status' => 'in_progress', 'created_by' => $owner->id,
]);
$p->users()->attach($owner->id, ['role_in_project' => 'supervisor']);
return $p;
}
public function test_global_manager_requires_manage_templates(): void
{
Permission::findOrCreate('manage templates');
$user = User::factory()->create(); // sin permiso
Livewire::actingAs($user)
->test(GlobalTemplateManager::class)
->assertForbidden();
}
public function test_global_manager_creates_template_without_project(): void
{
Permission::findOrCreate('manage templates');
$admin = User::factory()->create();
$admin->givePermissionTo('manage templates');
Livewire::actingAs($admin)
->test(GlobalTemplateManager::class)
->call('newTemplate')
->set('form.name', 'Inspección obra')
->call('saveTemplate')
->assertHasNoErrors();
$this->assertDatabaseHas('inspection_templates', [
'name' => 'Inspección obra', 'project_id' => null,
]);
}
public function test_picker_toggles_project_assignment(): void
{
Permission::findOrCreate('edit projects');
$user = User::factory()->create();
$user->givePermissionTo('edit projects');
$project = $this->project($user);
$tpl = InspectionTemplate::create(['name' => 'Recep', 'fields' => []]);
Livewire::actingAs($user)
->test(ProjectTemplatesPicker::class, ['project' => $project])
->call('toggle', $tpl->id);
$this->assertTrue($project->fresh()->inspectionTemplates()->where('inspection_templates.id', $tpl->id)->exists());
// Toggle de nuevo → desasigna
Livewire::actingAs($user)
->test(ProjectTemplatesPicker::class, ['project' => $project])
->call('toggle', $tpl->id);
$this->assertFalse($project->fresh()->inspectionTemplates()->where('inspection_templates.id', $tpl->id)->exists());
}
public function test_map_template_selector_only_shows_assigned_templates(): void
{
$user = User::factory()->create();
$project = $this->project($user, 'M');
$assigned = InspectionTemplate::create(['name' => 'Asignada', 'fields' => []]);
$unassigned = InspectionTemplate::create(['name' => 'Otra', 'fields' => []]);
$project->inspectionTemplates()->attach($assigned->id);
// Necesita una phase/layer al menos
Phase::create(['project_id' => $project->id, 'name' => 'F', 'order' => 1, 'color' => '#000', 'progress_percent' => 0]);
$cmp = Livewire::actingAs($user)
->test(ProjectMap::class, ['project' => $project]);
$names = collect($cmp->get('templates'))->pluck('name')->all();
$this->assertContains('Asignada', $names);
$this->assertNotContains('Otra', $names);
}
}
-110
View File
@@ -1,110 +0,0 @@
<?php
namespace Tests\Feature;
use App\Livewire\Inspections\TemplateManager;
use App\Models\Project;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Livewire\Livewire;
use Spatie\Permission\Models\Permission;
use Tests\TestCase;
class TemplateCreationTest extends TestCase
{
use RefreshDatabase;
private function setup_(): array
{
Permission::findOrCreate('edit projects');
$user = User::factory()->create();
$user->givePermissionTo('edit projects');
$project = Project::create([
'reference' => 'TPL-2', 'name' => 'Proyecto TPL', 'address' => 'x',
'lat' => 40.0, 'lng' => -3.0, 'start_date' => now()->toDateString(),
'end_date_estimated' => now()->addMonth()->toDateString(),
'status' => 'in_progress', 'created_by' => $user->id,
]);
return [$user, $project];
}
public function test_templates_page_embeds_the_manager_component(): void
{
[$user, $project] = $this->setup_();
$this->actingAs($user)
->get(route('projects.templates', $project))
->assertOk()
->assertSeeLivewire(TemplateManager::class);
}
public function test_new_template_button_opens_form_and_saves(): void
{
[$user, $project] = $this->setup_();
Livewire::actingAs($user)
->test(TemplateManager::class, ['project' => $project])
->assertSet('showForm', false)
->call('newTemplate')
->assertSet('showForm', true)
->set('form.name', 'Recepción de hormigón')
->call('saveTemplate')
->assertHasNoErrors();
$this->assertDatabaseHas('inspection_templates', [
'project_id' => $project->id,
'name' => 'Recepción de hormigón',
]);
}
public function test_field_keeps_group_question_and_help(): void
{
[$user, $project] = $this->setup_();
Livewire::actingAs($user)
->test(TemplateManager::class, ['project' => $project])
->call('newTemplate')
->set('form.name', 'Con grupos')
->call('addField')
->set('form.fields.0.group', 'Geometría')
->set('form.fields.0.name', 'altura')
->set('form.fields.0.label', 'Altura (m)')
->set('form.fields.0.question', '¿Cumple la cota?')
->set('form.fields.0.help', 'Medir con láser')
->call('saveTemplate')
->assertHasNoErrors();
$tpl = \App\Models\InspectionTemplate::where('name', 'Con grupos')->first();
$this->assertSame('Geometría', $tpl->fields[0]['group']);
$this->assertSame('¿Cumple la cota?', $tpl->fields[0]['question']);
$this->assertSame('Medir con láser', $tpl->fields[0]['help']);
}
public function test_global_template_has_no_project_and_shows_in_other_projects(): void
{
[$user, $project] = $this->setup_();
Livewire::actingAs($user)
->test(TemplateManager::class, ['project' => $project])
->call('newTemplate')
->set('form.name', 'Plantilla global')
->set('form.is_global', true)
->call('saveTemplate')
->assertHasNoErrors();
$this->assertDatabaseHas('inspection_templates', [
'name' => 'Plantilla global', 'project_id' => null,
]);
// Otro proyecto del mismo usuario ve la plantilla global en su listado
$other = \App\Models\Project::create([
'reference' => 'OTH', 'name' => 'Otro', 'address' => 'x', 'lat' => 40, 'lng' => -3,
'start_date' => now()->toDateString(), 'end_date_estimated' => now()->addMonth()->toDateString(),
'status' => 'in_progress', 'created_by' => $user->id,
]);
Livewire::actingAs($user)
->test(TemplateManager::class, ['project' => $other])
->assertSee('Plantilla global');
}
}
-91
View File
@@ -1,91 +0,0 @@
<?php
namespace Tests\Feature;
use App\Livewire\Inspections\TemplateManager;
use App\Livewire\Projects\ImportTemplatesTable;
use App\Models\InspectionTemplate;
use App\Models\Project;
use App\Models\User;
use Illuminate\Foundation\Testing\RefreshDatabase;
use Illuminate\Http\UploadedFile;
use Livewire\Livewire;
use Tests\TestCase;
class TemplateImportTest extends TestCase
{
use RefreshDatabase;
private function project(User $member, string $ref): Project
{
$p = Project::create([
'reference' => $ref, 'name' => 'Proyecto ' . $ref, 'address' => 'x',
'lat' => 40.0, 'lng' => -3.0, 'start_date' => now()->toDateString(),
'end_date_estimated' => now()->addMonth()->toDateString(),
'status' => 'in_progress', 'created_by' => $member->id,
]);
$p->users()->attach($member->id, ['role_in_project' => 'supervisor']);
return $p;
}
public function test_import_templates_from_another_project(): void
{
$user = User::factory()->create();
$source = $this->project($user, 'SRC');
$target = $this->project($user, 'DST');
$tpl = InspectionTemplate::create([
'project_id' => $source->id, 'name' => 'Recepción acero',
'fields' => [['name' => 'ok', 'label' => 'OK', 'type' => 'boolean']],
]);
// Tabla Rappasoft: lista plantillas de otros proyectos, selección con checkbox.
Livewire::actingAs($user)
->test(ImportTemplatesTable::class, ['projectId' => $target->id])
->assertSee('Recepción acero')
->set('selected', [(string) $tpl->id])
->call('importSelected')
->assertDispatched('templates-imported');
$this->assertDatabaseHas('inspection_templates', [
'project_id' => $target->id, 'name' => 'Recepción acero',
]);
}
public function test_import_table_excludes_target_project_templates(): void
{
$user = User::factory()->create();
$target = $this->project($user, 'DST2');
InspectionTemplate::create(['project_id' => $target->id, 'name' => 'Propia del destino', 'fields' => []]);
Livewire::actingAs($user)
->test(ImportTemplatesTable::class, ['projectId' => $target->id])
->assertDontSee('Propia del destino');
}
public function test_import_template_from_csv(): void
{
$user = User::factory()->create();
$project = $this->project($user, 'CSV');
$csv = "name,label,type,required,options,min,max,step\n"
. "resistencia,Resistencia,integer,1,,,,\n"
. "acabado,Acabado,select,0,bueno;regular;malo,,,\n";
$file = UploadedFile::fake()->createWithContent('campos.csv', $csv);
Livewire::actingAs($user)
->test(TemplateManager::class, ['project' => $project])
->call('openImportFileModal')
->set('importTemplateName', 'Plantilla CSV')
->set('importFile', $file)
->call('parseImportFile')
->assertHasNoErrors()
->call('confirmImportFile');
$this->assertDatabaseHas('inspection_templates', [
'project_id' => $project->id, 'name' => 'Plantilla CSV',
]);
$tpl = InspectionTemplate::where('name', 'Plantilla CSV')->first();
$this->assertCount(2, $tpl->fields);
}
}