chore: cleanup dead code + format with Pint

- Remove unused FeaturesController (empty stubs, no routes)
- Remove ConvertSpatialFile CLI command (unused; service used in LayerManager)
- Remove MigrateGeojsonToFeatures CLI command (one-shot migration, not referenced)
- Remove .claude/worktrees/ (11 old agent worktrees from June)
- Apply Laravel Pint formatting across 219 files (style only, no functional changes)

Tests: 101 passing (319 assertions)
API routes: unchanged (8 routes intact)
This commit is contained in:
Javier Braña
2026-08-28 13:04:28 +02:00
parent 2dccd59385
commit 90630379fb
139 changed files with 2888 additions and 2510 deletions
+12 -6
View File
@@ -14,13 +14,18 @@ use Livewire\Component;
class FeatureManager extends Component
{
public Project $project;
public $featureTypes = [];
// Edit modal
public bool $showForm = false;
public $editingId = null;
public string $name = '';
public $featureTypeId = '';
public bool $isActive = true;
public function mount(Project $project)
@@ -33,6 +38,7 @@ class FeatureManager extends Component
private function canManage(): bool
{
$user = Auth::user();
return $user->can('manage all')
|| ($user->can('edit layers') && $this->project->users()->where('user_id', $user->id)->exists());
}
@@ -42,10 +48,10 @@ class FeatureManager extends Component
{
abort_unless($this->canManage(), 403);
$feature = $this->findFeature($id);
$this->editingId = $feature->id;
$this->name = $feature->name ?? '';
$this->editingId = $feature->id;
$this->name = $feature->name ?? '';
$this->featureTypeId = $feature->feature_type_id ?? '';
$this->isActive = (bool) $feature->is_active;
$this->isActive = (bool) $feature->is_active;
$this->resetErrorBag();
$this->showForm = true;
}
@@ -54,14 +60,14 @@ class FeatureManager extends Component
{
abort_unless($this->canManage(), 403);
$this->validate([
'name' => 'required|string|max:255',
'name' => 'required|string|max:255',
'featureTypeId' => 'nullable|exists:feature_types,id',
]);
$this->findFeature($this->editingId)->update([
'name' => $this->name,
'name' => $this->name,
'feature_type_id' => $this->featureTypeId ?: null,
'is_active' => $this->isActive,
'is_active' => $this->isActive,
]);
$this->showForm = false;
+34 -32
View File
@@ -22,10 +22,10 @@ class FeatureTable extends DataTableComponent
public function configure(): void
{
$this->setPrimaryKey('id')
->setDefaultSort('name', 'asc')
->setSortingPillsEnabled(false)
->setSecondaryHeaderEnabled()
->setAdditionalSelects(['features.id as id', 'features.layer_id as layer_id']);
->setDefaultSort('name', 'asc')
->setSortingPillsEnabled(false)
->setSecondaryHeaderEnabled()
->setAdditionalSelects(['features.id as id', 'features.layer_id as layer_id']);
}
public function builder(): Builder
@@ -46,40 +46,42 @@ class FeatureTable extends DataTableComponent
{
return [
Column::make('Elemento', 'name')
->sortable()
->searchable()
->secondaryHeaderFilter('name')
->format(fn ($value) => '<span class="font-medium">' . e($value) . '</span>')
->html(),
->sortable()
->searchable()
->secondaryHeaderFilter('name')
->format(fn ($value) => '<span class="font-medium">'.e($value).'</span>')
->html(),
Column::make('Capa')
->secondaryHeaderFilter('layer')
->label(fn ($row) => e($row->layer?->name ?? '—')),
->secondaryHeaderFilter('layer')
->label(fn ($row) => e($row->layer?->name ?? '—')),
Column::make('Fase')
->secondaryHeaderFilter('phase')
->label(fn ($row) => e($row->layer?->phase?->name ?? '—')),
->secondaryHeaderFilter('phase')
->label(fn ($row) => e($row->layer?->phase?->name ?? '—')),
Column::make('Progreso', 'progress')
->sortable()
->format(function ($value) {
$cls = $value >= 100 ? 'badge-success' : ($value > 0 ? 'badge-warning' : 'badge-ghost');
return '<span class="badge badge-sm ' . $cls . '">' . (int) $value . '%</span>';
})
->html(),
->sortable()
->format(function ($value) {
$cls = $value >= 100 ? 'badge-success' : ($value > 0 ? 'badge-warning' : 'badge-ghost');
return '<span class="badge badge-sm '.$cls.'">'.(int) $value.'%</span>';
})
->html(),
Column::make('Acciones')
->label(function ($row) {
$id = $row->id;
return '<div class="flex justify-end">'
. '<button wire:click="$dispatch(\'map-select-feature\', { featureId: ' . $id . ' })"'
. 'class="btn btn-xs btn-primary gap-1" title="' . e(__('Editar elemento')) . '">'
. '<svg xmlns="http://www.w3.org/2000/svg" class="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"/></svg>'
. e(__('Abrir'))
. '</button>'
. '</div>';
})
->html(),
->label(function ($row) {
$id = $row->id;
return '<div class="flex justify-end">'
.'<button wire:click="$dispatch(\'map-select-feature\', { featureId: '.$id.' })"'
.'class="btn btn-xs btn-primary gap-1" title="'.e(__('Editar elemento')).'">'
.'<svg xmlns="http://www.w3.org/2000/svg" class="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"/></svg>'
.e(__('Abrir'))
.'</button>'
.'</div>';
})
->html(),
];
}
@@ -93,7 +95,7 @@ class FeatureTable extends DataTableComponent
return [
TextFilter::make('Elemento', 'name')
->config(['placeholder' => 'Buscar elemento…'])
->filter(fn (Builder $query, string $value) => $query->where('features.name', 'like', '%' . $value . '%')),
->filter(fn (Builder $query, string $value) => $query->where('features.name', 'like', '%'.$value.'%')),
SelectFilter::make('Capa', 'layer')
->options(['' => 'Todas'] + $layers)
@@ -104,4 +106,4 @@ class FeatureTable extends DataTableComponent
->filter(fn (Builder $query, string $value) => $query->whereHas('layer', fn ($l) => $l->where('phase_id', $value))),
];
}
}
}
+9 -5
View File
@@ -13,9 +13,13 @@ class FeatureTypeManager extends Component
public $types = [];
public bool $showForm = false;
public $editingId = null;
public string $name = '';
public string $description = '';
public string $color = '#6b7280';
public function mount()
@@ -32,9 +36,9 @@ class FeatureTypeManager extends Component
protected function rules(): array
{
return [
'name' => 'required|string|max:255|unique:feature_types,name,' . ($this->editingId ?? 'NULL'),
'name' => 'required|string|max:255|unique:feature_types,name,'.($this->editingId ?? 'NULL'),
'description' => 'nullable|string|max:255',
'color' => 'required|string|max:7',
'color' => 'required|string|max:7',
];
}
@@ -49,10 +53,10 @@ class FeatureTypeManager extends Component
public function edit($id): void
{
$t = FeatureType::findOrFail($id);
$this->editingId = $t->id;
$this->name = $t->name;
$this->editingId = $t->id;
$this->name = $t->name;
$this->description = $t->description ?? '';
$this->color = $t->color ?? '#6b7280';
$this->color = $t->color ?? '#6b7280';
$this->resetErrorBag();
$this->showForm = true;
}
+57 -59
View File
@@ -22,16 +22,16 @@ class InspectionTable extends DataTableComponent
public function configure(): void
{
$this->setPrimaryKey('id')
->setDefaultSort('inspections.created_at', 'desc')
->setSortingPillsEnabled(false)
->setSecondaryHeaderEnabled()
->setAdditionalSelects([
'inspections.id as id',
'inspections.created_at as created_at',
'inspections.feature_id as feature_id',
'inspections.template_id as template_id',
'inspections.user_id as user_id',
]);
->setDefaultSort('inspections.created_at', 'desc')
->setSortingPillsEnabled(false)
->setSecondaryHeaderEnabled()
->setAdditionalSelects([
'inspections.id as id',
'inspections.created_at as created_at',
'inspections.feature_id as feature_id',
'inspections.template_id as template_id',
'inspections.user_id as user_id',
]);
}
public function builder(): Builder
@@ -52,58 +52,57 @@ class InspectionTable extends DataTableComponent
{
return [
Column::make('Fecha', 'created_at')
->sortable()
->secondaryHeaderFilter('fecha')
->format(fn ($value, $row) => $row->created_at?->format('d/m/Y') ?? '—'),
->sortable()
->secondaryHeaderFilter('fecha')
->format(fn ($value, $row) => $row->created_at?->format('d/m/Y') ?? '—'),
Column::make('Elemento')
->secondaryHeaderFilter('elemento')
->label(fn ($row) => $row->feature?->name
? '<span class="font-medium">' . e($row->feature->name) . '</span>'
: '<span class="text-base-content/30 text-xs">—</span>')
->html(),
->secondaryHeaderFilter('elemento')
->label(fn ($row) => $row->feature?->name
? '<span class="font-medium">'.e($row->feature->name).'</span>'
: '<span class="text-base-content/30 text-xs">—</span>')
->html(),
Column::make('Plantilla')
->label(fn ($row) => e($row->template?->name ?? '—')),
->label(fn ($row) => e($row->template?->name ?? '—')),
Column::make('Resultado', 'result')
->sortable()
->secondaryHeaderFilter('resultado')
->format(fn ($value) => $value
? '<span class="badge badge-sm badge-outline">' . e($value) . '</span>'
: '<span class="text-base-content/30 text-xs">—</span>')
->html(),
->sortable()
->secondaryHeaderFilter('resultado')
->format(fn ($value) => $value
? '<span class="badge badge-sm badge-outline">'.e($value).'</span>'
: '<span class="text-base-content/30 text-xs">—</span>')
->html(),
Column::make('Usuario')
->secondaryHeaderFilter('usuario')
->label(fn ($row) => e($row->user?->name ?? '—')),
->secondaryHeaderFilter('usuario')
->label(fn ($row) => e($row->user?->name ?? '—')),
Column::make('Fotos')
->label(fn ($row) => $this->renderPhotosColumn($row))
->html(),
->label(fn ($row) => $this->renderPhotosColumn($row))
->html(),
Column::make('Acciones')
->label(fn ($row) =>
'<div class="flex justify-end gap-1">'
. '<button wire:click="$dispatch(\'map-view-inspection\', ' . $row->id . ')"'
. 'class="btn btn-xs btn-ghost" title="Ver inspección">'
. '<svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"/></svg>'
. '</button>'
. '@can("edit inspections")'
. '<button wire:click="$dispatch(\'edit-inspection\', ' . $row->id . ')"'
. 'class="btn btn-xs btn-ghost" title="Editar inspección">'
. '<svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"/></svg>'
. '</button>'
. '@endcan'
. '@can("delete inspections")'
. '<button wire:click="$dispatch(\'delete-inspection\', ' . $row->id . ')"'
. 'class="btn btn-xs btn-ghost btn-error" title="Eliminar inspección"'
. 'onclick="return confirm(\'¿Eliminar esta inspección? No se puede deshacer.\');">'
. '<svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16\"/></svg>'
. '</button>'
. '@endcan'
. '</div>')
->html(),
->label(fn ($row) => '<div class="flex justify-end gap-1">'
.'<button wire:click="$dispatch(\'map-view-inspection\', '.$row->id.')"'
.'class="btn btn-xs btn-ghost" title="Ver inspección">'
.'<svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z"/><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"/></svg>'
.'</button>'
.'@can("edit inspections")'
.'<button wire:click="$dispatch(\'edit-inspection\', '.$row->id.')"'
.'class="btn btn-xs btn-ghost" title="Editar inspección">'
.'<svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"/></svg>'
.'</button>'
.'@endcan'
.'@can("delete inspections")'
.'<button wire:click="$dispatch(\'delete-inspection\', '.$row->id.')"'
.'class="btn btn-xs btn-ghost btn-error" title="Eliminar inspección"'
.'onclick="return confirm(\'¿Eliminar esta inspección? No se puede deshacer.\');">'
.'<svg xmlns="http://www.w3.org/2000/svg" class="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16\"/></svg>'
.'</button>'
.'@endcan'
.'</div>')
->html(),
];
}
@@ -116,15 +115,14 @@ class InspectionTable extends DataTableComponent
return '<span class="text-base-content/30 text-xs">—</span>';
}
$thumbnails = $images->take(3)->map(fn ($m) =>
'<a href="' . $m->url . '" target="_blank" class="inline-block mr-1">'
. '<img src="' . $m->url . '" class="w-8 h-8 object-cover rounded border border-base-300" alt="' . e($m->name) . '" loading="lazy" />'
. '</a>'
$thumbnails = $images->take(3)->map(fn ($m) => '<a href="'.$m->url.'" target="_blank" class="inline-block mr-1">'
.'<img src="'.$m->url.'" class="w-8 h-8 object-cover rounded border border-base-300" alt="'.e($m->name).'" loading="lazy" />'
.'</a>'
)->implode('');
$more = $count > 3 ? '<span class="text-xs text-base-content/50 ml-1">+' . ($count - 3) . '</span>' : '';
$more = $count > 3 ? '<span class="text-xs text-base-content/50 ml-1">+'.($count - 3).'</span>' : '';
return '<div class="flex items-center">' . $thumbnails . $more . '</div>';
return '<div class="flex items-center">'.$thumbnails.$more.'</div>';
}
public function filters(): array
@@ -134,7 +132,7 @@ class InspectionTable extends DataTableComponent
->pluck('result', 'result')->toArray();
$users = User::whereIn('id', Inspection::where('project_id', $this->projectId)
->whereNotNull('user_id')->distinct()->pluck('user_id'))
->whereNotNull('user_id')->distinct()->pluck('user_id'))
->orderBy('name')->pluck('name', 'id')->toArray();
return [
@@ -143,7 +141,7 @@ class InspectionTable extends DataTableComponent
TextFilter::make('Elemento', 'elemento')
->config(['placeholder' => 'Buscar elemento…'])
->filter(fn (Builder $query, string $value) => $query->whereHas('feature', fn ($f) => $f->where('name', 'like', '%' . $value . '%'))),
->filter(fn (Builder $query, string $value) => $query->whereHas('feature', fn ($f) => $f->where('name', 'like', '%'.$value.'%'))),
SelectFilter::make('Resultado', 'resultado')
->options(['' => 'Todos'] + $results)
@@ -154,4 +152,4 @@ class InspectionTable extends DataTableComponent
->filter(fn (Builder $query, string $value) => $query->where('inspections.user_id', $value)),
];
}
}
}
+4 -1
View File
@@ -11,8 +11,11 @@ use Livewire\Component;
class ProjectCompanies extends Component
{
public Project $project;
public $allCompanies = [];
public $selectedCompanyId = '';
public $selectedRole = 'other';
public function mount(Project $project)
@@ -41,7 +44,7 @@ class ProjectCompanies extends Component
$this->validate([
'selectedCompanyId' => 'required|exists:companies,id',
'selectedRole' => 'required|in:' . implode(',', array_keys(ProjectCompaniesTable::ROLES)),
'selectedRole' => 'required|in:'.implode(',', array_keys(ProjectCompaniesTable::ROLES)),
]);
$this->project->companies()->attach($this->selectedCompanyId, [
+45 -41
View File
@@ -3,6 +3,7 @@
namespace App\Livewire\Projects;
use App\Models\Company;
use App\Models\Project;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Auth;
use Livewire\Attributes\On;
@@ -18,20 +19,20 @@ class ProjectCompaniesTable extends DataTableComponent
/** role_in_project => label */
public const ROLES = [
'owner' => 'Promotor',
'constructor' => 'Constructor',
'owner' => 'Promotor',
'constructor' => 'Constructor',
'subcontractor' => 'Subcontratista',
'consultant' => 'Consultor',
'supplier' => 'Proveedor',
'other' => 'Otro',
'consultant' => 'Consultor',
'supplier' => 'Proveedor',
'other' => 'Otro',
];
public function configure(): void
{
$this->setPrimaryKey('id')
->setDefaultSort('companies.name', 'asc')
->setSortingPillsEnabled(false)
->setAdditionalSelects(['companies.id as id', 'company_project.role_in_project as role_in_project']);
->setDefaultSort('companies.name', 'asc')
->setSortingPillsEnabled(false)
->setAdditionalSelects(['companies.id as id', 'company_project.role_in_project as role_in_project']);
}
#[On('project-companies-changed')]
@@ -51,48 +52,51 @@ class ProjectCompaniesTable extends DataTableComponent
{
return [
Column::make('Empresa', 'name')
->sortable()
->searchable()
->format(function ($value, $row) {
$initial = strtoupper(mb_substr($value ?? '?', 0, 1));
$html = '<div class="flex items-center gap-2">
->sortable()
->searchable()
->format(function ($value, $row) {
$initial = strtoupper(mb_substr($value ?? '?', 0, 1));
$html = '<div class="flex items-center gap-2">
<span class="w-7 h-7 rounded-full bg-primary text-primary-content flex items-center justify-center text-xs font-bold shrink-0">'.$initial.'</span>
<div><span class="font-medium">'.e($value).'</span>';
if ($row->tax_id) {
$html .= '<div class="text-xs text-base-content/50">'.e($row->tax_id).'</div>';
}
$html .= '</div></div>';
return $html;
})
->html(),
if ($row->tax_id) {
$html .= '<div class="text-xs text-base-content/50">'.e($row->tax_id).'</div>';
}
$html .= '</div></div>';
return $html;
})
->html(),
Column::make('Rol', 'role_in_project')
->label(function ($row) {
$current = $row->role_in_project;
if (! Auth::user()->can('assign companies')) {
return '<span class="badge badge-sm">'.(self::ROLES[$current] ?? ucfirst((string) $current)).'</span>';
}
$opts = '';
foreach (self::ROLES as $val => $label) {
$opts .= '<option value="'.$val.'"'.($current === $val ? ' selected' : '').'>'.$label.'</option>';
}
return '<select wire:change="changeRole('.$row->id.', $event.target.value)" class="select select-bordered select-xs">'.$opts.'</select>';
})
->html(),
->label(function ($row) {
$current = $row->role_in_project;
if (! Auth::user()->can('assign companies')) {
return '<span class="badge badge-sm">'.(self::ROLES[$current] ?? ucfirst((string) $current)).'</span>';
}
$opts = '';
foreach (self::ROLES as $val => $label) {
$opts .= '<option value="'.$val.'"'.($current === $val ? ' selected' : '').'>'.$label.'</option>';
}
return '<select wire:change="changeRole('.$row->id.', $event.target.value)" class="select select-bordered select-xs">'.$opts.'</select>';
})
->html(),
Column::make('Acciones')
->label(function ($row) {
if (! Auth::user()->can('assign companies')) {
return '';
}
return '<div class="flex justify-end">
->label(function ($row) {
if (! Auth::user()->can('assign companies')) {
return '';
}
return '<div class="flex justify-end">
<button wire:click="removeCompany('.$row->id.')" wire:confirm="¿Quitar a '.e($row->name).' del proyecto?"
class="btn btn-xs btn-error btn-outline" title="Quitar del proyecto">
<svg xmlns="http://www.w3.org/2000/svg" class="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/></svg>
</button>
</div>';
})
->html(),
})
->html(),
];
}
@@ -111,7 +115,7 @@ class ProjectCompaniesTable extends DataTableComponent
if (! array_key_exists($role, self::ROLES)) {
return;
}
\App\Models\Project::findOrFail($this->projectId)
Project::findOrFail($this->projectId)
->companies()->updateExistingPivot($companyId, ['role_in_project' => $role]);
$this->dispatch('project-companies-changed');
$this->dispatch('notify', 'Rol actualizado.');
@@ -120,7 +124,7 @@ class ProjectCompaniesTable extends DataTableComponent
public function removeCompany($companyId): void
{
abort_unless(Auth::user()->can('assign companies'), 403);
\App\Models\Project::findOrFail($this->projectId)->companies()->detach($companyId);
Project::findOrFail($this->projectId)->companies()->detach($companyId);
$this->dispatch('project-companies-changed');
$this->dispatch('notify', 'Empresa eliminada del proyecto.');
}
+38 -30
View File
@@ -2,14 +2,14 @@
namespace App\Livewire\Projects;
use Livewire\Component;
use Livewire\Attributes\Layout;
use App\Models\Project;
use App\Models\Phase;
use App\Models\Feature;
use App\Models\Inspection;
use App\Models\Issue;
use App\Models\Phase;
use App\Models\Project;
use Illuminate\Support\Facades\Auth;
use Livewire\Attributes\Layout;
use Livewire\Component;
#[Layout('layouts.app')]
class ProjectDashboard extends Component
@@ -17,11 +17,16 @@ class ProjectDashboard extends Component
public Project $project;
// Computed stats (cached as properties after mount)
public array $stats = [];
public array $stats = [];
public $phases;
public $recentInspections;
public $recentIssues;
public $teamMembers;
public $companies;
public function mount(Project $project): void
@@ -34,8 +39,12 @@ class ProjectDashboard extends Component
private function checkAccess(): void
{
$user = Auth::user();
if ($user->can('manage all')) return;
if (!$this->project->users()->where('user_id', $user->id)->exists()) abort(403);
if ($user->can('manage all')) {
return;
}
if (! $this->project->users()->where('user_id', $user->id)->exists()) {
abort(403);
}
}
private function loadData(): void
@@ -44,43 +53,42 @@ class ProjectDashboard extends Component
$this->phases = Phase::where('project_id', $pid)
->withCount('layers')
->with(['layers' => fn($q) => $q->withCount('features')])
->with(['layers' => fn ($q) => $q->withCount('features')])
->orderBy('order')
->get();
$totalFeatures = Feature::whereHas('layer.phase', fn($q) => $q->where('project_id', $pid))->count();
$completedFeatures = Feature::whereHas('layer.phase', fn($q) => $q->where('project_id', $pid))
$totalFeatures = Feature::whereHas('layer.phase', fn ($q) => $q->where('project_id', $pid))->count();
$completedFeatures = Feature::whereHas('layer.phase', fn ($q) => $q->where('project_id', $pid))
->where('status', 'completed')->count();
$verifiedFeatures = Feature::whereHas('layer.phase', fn($q) => $q->where('project_id', $pid))
$verifiedFeatures = Feature::whereHas('layer.phase', fn ($q) => $q->where('project_id', $pid))
->where('status', 'verified')->count();
$openIssues = Issue::where('project_id', $pid)->where('status', 'open')->count();
$closedIssues = Issue::where('project_id', $pid)->where('status', 'closed')->count();
$openIssues = Issue::where('project_id', $pid)->where('status', 'open')->count();
$closedIssues = Issue::where('project_id', $pid)->where('status', 'closed')->count();
$criticalIssues = Issue::where('project_id', $pid)->where('status', 'open')->where('priority', 'critical')->count();
$totalInspections = Inspection::where('project_id', $pid)->count();
$passedInspections = Inspection::where('project_id', $pid)->where('result', 'pass')->count();
$failedInspections = Inspection::where('project_id', $pid)->where('result', 'fail')->count();
$totalInspections = Inspection::where('project_id', $pid)->count();
$passedInspections = Inspection::where('project_id', $pid)->where('result', 'pass')->count();
$failedInspections = Inspection::where('project_id', $pid)->where('result', 'fail')->count();
$globalProgress = $this->phases->avg('progress_percent') ?? 0;
$delayedPhases = $this->phases->filter(fn($p) =>
$p->planned_end && $p->planned_end < now() && $p->progress_percent < 100
$delayedPhases = $this->phases->filter(fn ($p) => $p->planned_end && $p->planned_end < now() && $p->progress_percent < 100
)->count();
$this->stats = [
'global_progress' => round($globalProgress),
'total_phases' => $this->phases->count(),
'delayed_phases' => $delayedPhases,
'total_features' => $totalFeatures,
'completed_features' => $completedFeatures,
'verified_features' => $verifiedFeatures,
'open_issues' => $openIssues,
'closed_issues' => $closedIssues,
'critical_issues' => $criticalIssues,
'total_inspections' => $totalInspections,
'passed_inspections' => $passedInspections,
'failed_inspections' => $failedInspections,
'global_progress' => round($globalProgress),
'total_phases' => $this->phases->count(),
'delayed_phases' => $delayedPhases,
'total_features' => $totalFeatures,
'completed_features' => $completedFeatures,
'verified_features' => $verifiedFeatures,
'open_issues' => $openIssues,
'closed_issues' => $closedIssues,
'critical_issues' => $criticalIssues,
'total_inspections' => $totalInspections,
'passed_inspections' => $passedInspections,
'failed_inspections' => $failedInspections,
];
$this->recentInspections = Inspection::where('project_id', $pid)
+33 -31
View File
@@ -4,6 +4,7 @@ namespace App\Livewire\Projects;
use App\Models\Feature;
use App\Models\FeatureType;
use App\Models\Layer;
use App\Models\Project;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Auth;
@@ -22,10 +23,10 @@ class ProjectFeaturesTable extends DataTableComponent
public function configure(): void
{
$this->setPrimaryKey('id')
->setDefaultSort('name', 'asc')
->setSortingPillsEnabled(false)
->setSecondaryHeaderEnabled()
->setAdditionalSelects(['features.id as id', 'features.layer_id as layer_id', 'features.feature_type_id as feature_type_id']);
->setDefaultSort('name', 'asc')
->setSortingPillsEnabled(false)
->setSecondaryHeaderEnabled()
->setAdditionalSelects(['features.id as id', 'features.layer_id as layer_id', 'features.feature_type_id as feature_type_id']);
}
#[On('features-changed')]
@@ -37,6 +38,7 @@ class ProjectFeaturesTable extends DataTableComponent
private function canManage(): bool
{
$user = Auth::user();
return $user->can('manage all') ||
($user->can('edit layers') &&
Project::whereKey($this->projectId)->whereHas('users', fn ($q) => $q->where('user_id', $user->id))->exists());
@@ -55,47 +57,47 @@ class ProjectFeaturesTable extends DataTableComponent
{
return [
Column::make('Elemento', 'name')
->sortable()->searchable()
->secondaryHeaderFilter('name')
->format(fn ($value) => '<span class="font-medium">' . e($value) . '</span>')
->html(),
->sortable()->searchable()
->secondaryHeaderFilter('name')
->format(fn ($value) => '<span class="font-medium">'.e($value).'</span>')
->html(),
Column::make('Capa')
->secondaryHeaderFilter('layer')
->label(fn ($row) => e($row->layer?->name ?? '—')),
->secondaryHeaderFilter('layer')
->label(fn ($row) => e($row->layer?->name ?? '—')),
Column::make('Fase')
->label(fn ($row) => e($row->layer?->phase?->name ?? '—')),
->label(fn ($row) => e($row->layer?->phase?->name ?? '—')),
Column::make('Tipo')
->secondaryHeaderFilter('type')
->label(fn ($row) => $row->featureType
? '<span class="badge badge-sm" style="background-color:' . e($row->featureType->color) . ';color:#fff;border:0;">' . e($row->featureType->name) . '</span>'
: '<span class="text-base-content/30 text-xs">—</span>')
->html(),
->secondaryHeaderFilter('type')
->label(fn ($row) => $row->featureType
? '<span class="badge badge-sm" style="background-color:'.e($row->featureType->color).';color:#fff;border:0;">'.e($row->featureType->name).'</span>'
: '<span class="text-base-content/30 text-xs">—</span>')
->html(),
Column::make('Activo', 'is_active')
->sortable()
->label(function ($row) {
if ($row->is_active) {
return '<button wire:click="toggleActive(' . $row->id . ')" class="badge badge-success badge-sm" title="Desactivar">Activo</button>';
}
return '<button wire:click="toggleActive(' . $row->id . ')" class="badge badge-ghost badge-sm" title="Activar">Inactivo</button>';
})
->html(),
->sortable()
->label(function ($row) {
if ($row->is_active) {
return '<button wire:click="toggleActive('.$row->id.')" class="badge badge-success badge-sm" title="Desactivar">Activo</button>';
}
return '<button wire:click="toggleActive('.$row->id.')" class="badge badge-ghost badge-sm" title="Activar">Inactivo</button>';
})
->html(),
Column::make('Acciones')
->label(fn ($row) =>
'<div class="flex justify-end gap-1">
<button wire:click="$dispatch(\'feature-edit\', { id: ' . $row->id . ' })" class="btn btn-xs btn-ghost" title="Editar">
->label(fn ($row) => '<div class="flex justify-end gap-1">
<button wire:click="$dispatch(\'feature-edit\', { id: '.$row->id.' })" class="btn btn-xs btn-ghost" title="Editar">
<svg xmlns="http://www.w3.org/2000/svg" class="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"/></svg>
</button>
<button wire:click="deleteFeature(' . $row->id . ')" wire:confirm="¿Eliminar el elemento \'' . e($row->name) . '\'? Esta acción no se puede deshacer."
<button wire:click="deleteFeature('.$row->id.')" wire:confirm="¿Eliminar el elemento \''.e($row->name).'\'? Esta acción no se puede deshacer."
class="btn btn-xs btn-error btn-outline" title="Eliminar">
<svg xmlns="http://www.w3.org/2000/svg" class="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16"/></svg>
</button>
</div>')
->html(),
->html(),
];
}
@@ -105,10 +107,10 @@ class ProjectFeaturesTable extends DataTableComponent
return [
TextFilter::make('Elemento', 'name')
->filter(fn (Builder $q, string $v) => $q->where('features.name', 'like', '%' . $v . '%')),
->filter(fn (Builder $q, string $v) => $q->where('features.name', 'like', '%'.$v.'%')),
SelectFilter::make('Capa', 'layer')
->options(['' => 'Todas'] + \App\Models\Layer::whereHas('phase', fn ($q) => $q->where('project_id', $this->projectId))->orderBy('name')->pluck('name', 'id')->toArray())
->options(['' => 'Todas'] + Layer::whereHas('phase', fn ($q) => $q->where('project_id', $this->projectId))->orderBy('name')->pluck('name', 'id')->toArray())
->filter(fn (Builder $q, string $v) => $q->where('features.layer_id', $v)),
SelectFilter::make('Tipo', 'type')
+54 -44
View File
@@ -2,12 +2,12 @@
namespace App\Livewire\Projects;
use Livewire\Component;
use Livewire\Attributes\Layout;
use Livewire\Attributes\On;
use App\Models\Project;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Gate;
use Livewire\Attributes\Layout;
use Livewire\Attributes\On;
use Livewire\Component;
#[Layout('layouts.app')]
class ProjectForm extends Component
@@ -15,33 +15,39 @@ class ProjectForm extends Component
public ?Project $project = null;
// Identification
public string $name = '';
public string $name = '';
public string $reference = '';
public string $status = 'planning';
public string $status = 'planning';
// Location
public string $address = '';
public string $country = '';
public string $lat = '';
public string $lng = '';
public string $lat = '';
public string $lng = '';
// Planning
public string $startDate = '';
public string $endDateEstimated = '';
public string $startDate = '';
public string $endDateEstimated = '';
public function mount(?Project $project = null): void
{
if ($project && $project->exists) {
Gate::authorize('edit projects', $project);
$this->project = $project;
$this->name = $project->name;
$this->reference = $project->reference ?? '';
$this->status = $project->status;
$this->address = $project->address;
$this->country = $project->country ?? '';
$this->lat = (string) ($project->lat ?? '');
$this->lng = (string) ($project->lng ?? '');
$this->startDate = $project->start_date->format('Y-m-d');
$this->project = $project;
$this->name = $project->name;
$this->reference = $project->reference ?? '';
$this->status = $project->status;
$this->address = $project->address;
$this->country = $project->country ?? '';
$this->lat = (string) ($project->lat ?? '');
$this->lng = (string) ($project->lng ?? '');
$this->startDate = $project->start_date->format('Y-m-d');
$this->endDateEstimated = $project->end_date_estimated?->format('Y-m-d') ?? '';
} else {
Gate::authorize('create projects');
@@ -56,34 +62,38 @@ class ProjectForm extends Component
{
$this->lat = $lat;
$this->lng = $lng;
if ($address) $this->address = $address;
if ($country) $this->country = strtolower($country);
if ($address) {
$this->address = $address;
}
if ($country) {
$this->country = strtolower($country);
}
}
protected function rules(): array
{
return [
'name' => 'required|string|max:255',
'reference' => 'nullable|string|max:100',
'status' => 'required|in:planning,in_progress,paused,completed',
'address' => 'required|string',
'country' => 'nullable|string|size:2',
'lat' => 'nullable|numeric|between:-90,90',
'lng' => 'nullable|numeric|between:-180,180',
'startDate' => 'required|date',
'name' => 'required|string|max:255',
'reference' => 'nullable|string|max:100',
'status' => 'required|in:planning,in_progress,paused,completed',
'address' => 'required|string',
'country' => 'nullable|string|size:2',
'lat' => 'nullable|numeric|between:-90,90',
'lng' => 'nullable|numeric|between:-180,180',
'startDate' => 'required|date',
'endDateEstimated' => 'nullable|date|after_or_equal:startDate',
];
}
protected $validationAttributes = [
'name' => 'nombre',
'reference' => 'referencia',
'status' => 'estado',
'address' => 'dirección',
'country' => 'país',
'lat' => 'latitud',
'lng' => 'longitud',
'startDate' => 'fecha de inicio',
'name' => 'nombre',
'reference' => 'referencia',
'status' => 'estado',
'address' => 'dirección',
'country' => 'país',
'lat' => 'latitud',
'lng' => 'longitud',
'startDate' => 'fecha de inicio',
'endDateEstimated' => 'fecha de fin estimada',
];
@@ -92,14 +102,14 @@ class ProjectForm extends Component
$this->validate();
$data = [
'name' => $this->name,
'reference' => $this->reference ?: null,
'status' => $this->status,
'address' => $this->address,
'country' => $this->country ?: null,
'lat' => $this->lat ?: null,
'lng' => $this->lng ?: null,
'start_date' => $this->startDate,
'name' => $this->name,
'reference' => $this->reference ?: null,
'status' => $this->status,
'address' => $this->address,
'country' => $this->country ?: null,
'lat' => $this->lat ?: null,
'lng' => $this->lng ?: null,
'start_date' => $this->startDate,
'end_date_estimated' => $this->endDateEstimated ?: null,
];
+7 -5
View File
@@ -2,11 +2,11 @@
namespace App\Livewire\Projects;
use Livewire\Component;
use Livewire\WithPagination;
use Livewire\Attributes\Layout;
use App\Models\Project;
use Illuminate\Support\Facades\Auth;
use Livewire\Attributes\Layout;
use Livewire\Component;
use Livewire\WithPagination;
#[Layout('layouts.app')]
class ProjectList extends Component
@@ -14,6 +14,7 @@ class ProjectList extends Component
use WithPagination;
public $search = '';
public $statusFilter = '';
public function deleteProject($id)
@@ -29,12 +30,13 @@ class ProjectList extends Component
{
$query = Project::accessibleBy(Auth::user());
if ($this->search) {
$query->where('name', 'like', '%' . $this->search . '%');
$query->where('name', 'like', '%'.$this->search.'%');
}
if ($this->statusFilter) {
$query->where('status', $this->statusFilter);
}
$projects = $query->with('phases')->latest()->paginate(10);
return view('livewire.projects.project-list', ['projects' => $projects]);
}
}
}
+252 -136
View File
@@ -2,63 +2,86 @@
namespace App\Livewire\Projects;
use Livewire\Component;
use Livewire\Attributes\On;
use Livewire\WithFileUploads;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Log;
use App\Models\Project;
use App\Models\Phase;
use App\Models\Layer;
use App\Models\Feature;
use App\Models\Inspection;
use App\Models\InspectionTemplate;
use App\Models\Issue;
use App\Models\Layer;
use App\Models\Media;
use App\Models\Phase;
use App\Models\Project;
use App\Notifications\InspectionCompletedNotification;
use App\Notifications\InspectionDeletedNotification;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Str;
use Livewire\Attributes\On;
use Livewire\Component;
use Livewire\WithFileUploads;
class ProjectMap extends Component
{
use WithFileUploads;
public Project $project;
public $phases;
public $activeLayers = []; // Now stores Layer IDs (not Phase IDs)
public $showLayerModal = false;
// Editor properties
public $selectedFeature = null;
public $selectedPhaseId = null;
public $editProgress = 0;
public $editComment = '';
public $editResponsible = '';
public $editPhotos = [];
public $formFullscreen = false;
// Tab management
public $activeTab = 'edit';
public $allFeatures;
public $allInspections;
// Templates e inspecciones
public $templates = [];
public $selectedTemplateId = null;
public $inspectionFormData = [];
public $inspectionHistory = [];
// Imágenes en mapa
public $showFeatureImages = false;
public $featureImageMarkers = [];
// Filters
public $filterStatus = '';
public $filterResponsible = '';
public $filterProgressMin = 0;
public $filterProgressMax = 100;
public $showFilters = false;
// Inspection workflow
public $inspectionResult = '';
public $inspectionNotes = '';
public $inspectionPhotos = [];
// Issues
@@ -69,10 +92,15 @@ class ProjectMap extends Component
// Inspection editor (para editar inspecciones existentes)
public $editingInspection = null;
public $editInspectionFormData = [];
public $editInspectionResult = '';
public $editInspectionNotes = '';
public $editInspectionPhotos = [];
public $editInspectionPhotosToDelete = [];
public function mount(Project $project)
@@ -81,20 +109,20 @@ class ProjectMap extends Component
$this->authorizeProjectAccess();
$this->phases = $project->phases()->with([
'layers' => fn($q) => $q->withCount('features'),
'layers' => fn ($q) => $q->withCount('features'),
'layers.features',
'layers.features.images',
])->get();
// Initialize activeLayers with ALL layer IDs (not phase IDs)
$this->activeLayers = $this->phases
->flatMap(fn($p) => $p->layers->pluck('id'))
->map(fn($id) => (int) $id)
->flatMap(fn ($p) => $p->layers->pluck('id'))
->map(fn ($id) => (int) $id)
->toArray();
$this->loadTemplates();
$this->allFeatures = Feature::whereHas('layer.phase', function($q) use ($project) {
$this->allFeatures = Feature::whereHas('layer.phase', function ($q) use ($project) {
$q->where('project_id', $project->id);
})->with(['layer.phase', 'template'])->get();
@@ -111,8 +139,12 @@ class ProjectMap extends Component
private function authorizeProjectAccess(): void
{
$user = Auth::user();
if ($user->can('manage all')) return;
if (!$this->project->users()->where('user_id', $user->id)->exists()) abort(403);
if ($user->can('manage all')) {
return;
}
if (! $this->project->users()->where('user_id', $user->id)->exists()) {
abort(403);
}
}
public function loadTemplates()
@@ -139,9 +171,11 @@ class ProjectMap extends Component
public function togglePhase($phaseId)
{
$phase = $this->phases->find($phaseId);
if (!$phase) return;
$layerIds = $phase->layers->pluck('id')->map(fn($id) => (int) $id)->toArray();
$allActive = !empty($layerIds) && collect($layerIds)->every(fn($id) => in_array($id, $this->activeLayers));
if (! $phase) {
return;
}
$layerIds = $phase->layers->pluck('id')->map(fn ($id) => (int) $id)->toArray();
$allActive = ! empty($layerIds) && collect($layerIds)->every(fn ($id) => in_array($id, $this->activeLayers));
if ($allActive) {
$this->activeLayers = array_values(array_diff($this->activeLayers, $layerIds));
} else {
@@ -150,22 +184,51 @@ class ProjectMap extends Component
$this->dispatch('layersUpdated', $this->activeLayers);
}
public function openLayerModal() { $this->showLayerModal = true; }
public function closeLayerModal() { $this->showLayerModal = false; }
public function openLayerModal()
{
$this->showLayerModal = true;
}
public function closeLayerModal()
{
$this->showLayerModal = false;
}
// ─── Filters ────────────────────────────────────────────────────────────────
public function updatedFilterStatus() { $this->applyFilters(); }
public function updatedFilterResponsible() { $this->applyFilters(); }
public function updatedFilterProgressMin() { $this->applyFilters(); }
public function updatedFilterProgressMax() { $this->applyFilters(); }
public function updatedFilterStatus()
{
$this->applyFilters();
}
public function updatedFilterResponsible()
{
$this->applyFilters();
}
public function updatedFilterProgressMin()
{
$this->applyFilters();
}
public function updatedFilterProgressMax()
{
$this->applyFilters();
}
public function applyFilters()
{
$filtered = $this->allFeatures->filter(function($f) {
if ($this->filterStatus && $f->status !== $this->filterStatus) return false;
if ($this->filterResponsible && !str_contains(strtolower($f->responsible ?? ''), strtolower($this->filterResponsible))) return false;
if ($f->progress < $this->filterProgressMin || $f->progress > $this->filterProgressMax) return false;
$filtered = $this->allFeatures->filter(function ($f) {
if ($this->filterStatus && $f->status !== $this->filterStatus) {
return false;
}
if ($this->filterResponsible && ! str_contains(strtolower($f->responsible ?? ''), strtolower($this->filterResponsible))) {
return false;
}
if ($f->progress < $this->filterProgressMin || $f->progress > $this->filterProgressMax) {
return false;
}
return true;
});
$this->dispatch('filtersChanged', $filtered->pluck('id')->values()->toArray());
@@ -184,16 +247,24 @@ class ProjectMap extends Component
public function editFeatureStatus($status)
{
if (!$this->selectedFeature) return;
if (! $this->selectedFeature) {
return;
}
$feature = Feature::with('layer.phase')->findOrFail($this->selectedFeature->id);
if ($feature->layer->phase->project_id !== $this->project->id) abort(403);
if ($feature->layer->phase->project_id !== $this->project->id) {
abort(403);
}
$feature->status = $status;
if ($status === 'completed') $feature->progress = 100;
if ($status === 'planned') $feature->progress = 0;
if ($status === 'completed') {
$feature->progress = 100;
}
if ($status === 'planned') {
$feature->progress = 0;
}
$feature->save();
$this->selectedFeature = $feature;
$this->editProgress = $feature->progress;
$this->allFeatures = $this->allFeatures->map(fn($f) => $f->id === $feature->id ? $feature : $f);
$this->allFeatures = $this->allFeatures->map(fn ($f) => $f->id === $feature->id ? $feature : $f);
$this->dispatch('featureStatusChanged', $feature->id, $feature->status, $feature->status_color);
$this->dispatch('notify', 'Estado actualizado');
}
@@ -202,20 +273,23 @@ class ProjectMap extends Component
{
$feature = Feature::with('layer.phase')->findOrFail($featureId);
$user = Auth::user();
if (!$user->can('update progress')) {
if (! $user->can('update progress')) {
$this->dispatch('notify', 'Sin permisos');
return;
}
if ($feature->layer->phase->project_id !== $this->project->id) abort(403);
if ($feature->layer->phase->project_id !== $this->project->id) {
abort(403);
}
$feature->progress = min(100, max(0, $newProgress));
$feature->save();
$phase = $feature->layer->phase;
$phase->progress_percent = $phase->features()->avg('progress') ?: 0;
$phase->save();
$phase->progressUpdates()->create([
'user_id' => $user->id,
'user_id' => $user->id,
'progress_percent' => $phase->progress_percent,
'comment' => $comment,
'comment' => $comment,
]);
$this->dispatch('progressUpdated', $featureId, $feature->progress);
$this->dispatch('notify', 'Progreso actualizado');
@@ -228,25 +302,33 @@ class ProjectMap extends Component
#[On('map-select-feature')]
public function selectFeature($featureId)
{
\Log::info('map-select-feature received', ['payload' => $featureId]);
\Log::info('[ProjectMap] map-select-feature received', ['payload' => $featureId, 'type' => gettype($featureId)]);
// Handle both formats: direct ID or { featureId: X }
if (is_array($featureId) && isset($featureId['featureId'])) {
$featureId = $featureId['featureId'];
\Log::info('[ProjectMap] Extracted featureId from array', ['featureId' => $featureId]);
}
$this->selectedFeature = null;
$feature = Feature::with(['template', 'layer.phase'])->find($featureId);
if (!$feature) return;
if ($feature->layer->phase->project_id !== $this->project->id) abort(403);
if (! $feature) {
\Log::warning('[ProjectMap] Feature not found', ['featureId' => $featureId]);
$this->selectedFeature = $feature;
$this->selectedPhaseId = $feature->layer->phase_id;
$this->editProgress = $feature->progress;
$this->editResponsible = $feature->responsible ?? '';
$this->editPhotos = $feature->properties['photos'] ?? [];
return;
}
if ($feature->layer->phase->project_id !== $this->project->id) {
\Log::warning('[ProjectMap] Feature not in project', ['featureId' => $featureId, 'projectId' => $this->project->id]);
abort(403);
}
$this->selectedFeature = $feature;
$this->selectedPhaseId = $feature->layer->phase_id;
$this->editProgress = $feature->progress;
$this->editResponsible = $feature->responsible ?? '';
$this->editPhotos = $feature->properties['photos'] ?? [];
$this->selectedTemplateId = $feature->template_id;
$this->activeTab = 'edit';
$this->activeTab = 'edit';
$this->loadInspectionHistory();
$this->resetInspectionForm();
@@ -256,8 +338,9 @@ class ProjectMap extends Component
public function loadInspectionHistory()
{
if (!$this->selectedFeature) {
if (! $this->selectedFeature) {
$this->inspectionHistory = [];
return;
}
$this->inspectionHistory = Inspection::where('feature_id', $this->selectedFeature->id)
@@ -269,9 +352,9 @@ class ProjectMap extends Component
public function resetInspectionForm()
{
$this->inspectionFormData = [];
$this->inspectionResult = '';
$this->inspectionNotes = '';
$this->inspectionPhotos = [];
$this->inspectionResult = '';
$this->inspectionNotes = '';
$this->inspectionPhotos = [];
if ($this->selectedTemplateId) {
$template = InspectionTemplate::find($this->selectedTemplateId);
if ($template) {
@@ -284,45 +367,50 @@ class ProjectMap extends Component
public function saveInspection()
{
if (!$this->selectedFeature || !$this->selectedTemplateId) {
if (! $this->selectedFeature || ! $this->selectedTemplateId) {
$this->dispatch('notify', 'Selecciona un elemento y un template.');
return;
}
// Verificar permiso
if (!auth()->user()->can('create inspections')) {
if (! auth()->user()->can('create inspections')) {
$this->dispatch('notify', 'Sin permisos para crear inspecciones.');
return;
}
$feature = Feature::with('layer.phase')->find($this->selectedFeature->id);
if (!$feature || $feature->layer->phase->project_id !== $this->project->id) abort(403);
if (! $feature || $feature->layer->phase->project_id !== $this->project->id) {
abort(403);
}
$this->validate([
'selectedTemplateId' => 'required|exists:inspection_templates,id',
'inspectionPhotos.*' => 'nullable|image|mimes:jpeg,png,jpg,webp|max:10240',
'selectedTemplateId' => 'required|exists:inspection_templates,id',
'inspectionPhotos.*' => 'nullable|image|mimes:jpeg,png,jpg,webp|max:10240',
]);
$template = InspectionTemplate::find($this->selectedTemplateId);
foreach ($template->fields as $field) {
if (($field['required'] ?? false) && empty($this->inspectionFormData[$field['name']])) {
$this->dispatch('notify', "El campo {$field['label']} es obligatorio.");
return;
}
}
$inspection = Inspection::create([
'project_id' => $this->project->id,
'layer_id' => $this->selectedFeature->layer_id,
'feature_id' => $this->selectedFeature->id,
'template_id' => $this->selectedTemplateId,
'user_id' => auth()->id(),
'project_id' => $this->project->id,
'layer_id' => $this->selectedFeature->layer_id,
'feature_id' => $this->selectedFeature->id,
'template_id' => $this->selectedTemplateId,
'user_id' => auth()->id(),
'inspector_user_id' => auth()->id(),
'status' => 'completed',
'completed_at' => now(),
'result' => $this->inspectionResult ?: null,
'notes' => $this->inspectionNotes ?: null,
'data' => $this->inspectionFormData,
'status' => 'completed',
'completed_at' => now(),
'result' => $this->inspectionResult ?: null,
'notes' => $this->inspectionNotes ?: null,
'data' => $this->inspectionFormData,
]);
// Fotos adjuntas a la inspección
@@ -330,34 +418,34 @@ class ProjectMap extends Component
$mime = $photo->getMimeType();
$path = $photo->store("uploads/inspections/{$inspection->id}", 'public');
$inspection->media()->create([
'name' => $photo->getClientOriginalName(),
'file_path' => $path,
'file_type' => $mime,
'name' => $photo->getClientOriginalName(),
'file_path' => $path,
'file_type' => $mime,
'file_extension' => $photo->getClientOriginalExtension(),
'file_size' => $photo->getSize(),
'category' => str_starts_with($mime, 'image/') ? 'image' : 'document',
'uploaded_by' => auth()->id(),
'uuid' => (string) \Illuminate\Support\Str::uuid(),
'file_size' => $photo->getSize(),
'category' => str_starts_with($mime, 'image/') ? 'image' : 'document',
'uploaded_by' => auth()->id(),
'uuid' => (string) Str::uuid(),
]);
}
if ($this->inspectionResult === 'fail') {
Issue::create([
'project_id' => $this->project->id,
'feature_id' => $this->selectedFeature->id,
'project_id' => $this->project->id,
'feature_id' => $this->selectedFeature->id,
'inspection_id' => $inspection->id,
'title' => 'Fallo en inspección: ' . ($template->name ?? 'Sin nombre'),
'description' => $this->inspectionNotes,
'priority' => 'high',
'status' => 'open',
'reported_by' => auth()->id(),
'title' => 'Fallo en inspección: '.($template->name ?? 'Sin nombre'),
'description' => $this->inspectionNotes,
'priority' => 'high',
'status' => 'open',
'reported_by' => auth()->id(),
]);
$this->openIssuesCount = Issue::where('project_id', $this->project->id)
->where('status', 'open')->count();
$this->dispatch('notify', 'Inspección fallida — Issue creado automáticamente');
} else {
if (isset($this->inspectionFormData['progress'])) {
$this->updateProgress($this->selectedFeature->id, (int)$this->inspectionFormData['progress'], 'Inspección registrada');
$this->updateProgress($this->selectedFeature->id, (int) $this->inspectionFormData['progress'], 'Inspección registrada');
}
$this->dispatch('notify', 'Inspección guardada correctamente');
}
@@ -367,7 +455,7 @@ class ProjectMap extends Component
->where('user_id', '!=', auth()->id())
->get();
foreach ($usersToNotify as $user) {
$user->notify(new \App\Notifications\InspectionCompletedNotification($inspection));
$user->notify(new InspectionCompletedNotification($inspection));
}
// Reload global list
@@ -382,14 +470,18 @@ class ProjectMap extends Component
public function assignTemplateToFeature($templateId)
{
if (!$this->selectedFeature) return;
if (! $this->selectedFeature) {
return;
}
$template = InspectionTemplate::where('id', $templateId)
->where('project_id', $this->project->id)->first();
if (!$template) abort(403);
if (! $template) {
abort(403);
}
$feature = Feature::findOrFail($this->selectedFeature->id);
$feature->template_id = $templateId;
$feature->save();
$this->selectedFeature = $feature;
$this->selectedFeature = $feature;
$this->selectedTemplateId = $templateId;
$this->resetInspectionForm();
$this->dispatch('notify', 'Template asignado al elemento');
@@ -397,10 +489,14 @@ class ProjectMap extends Component
public function saveFeatureProgress()
{
if (!$this->selectedFeature) return;
if (! $this->selectedFeature) {
return;
}
$feature = Feature::with('layer.phase')->findOrFail($this->selectedFeature->id);
if ($feature->layer->phase->project_id !== $this->project->id) abort(403);
$feature->progress = min(100, max(0, (int)$this->editProgress));
if ($feature->layer->phase->project_id !== $this->project->id) {
abort(403);
}
$feature->progress = min(100, max(0, (int) $this->editProgress));
$feature->responsible = $this->editResponsible;
$feature->save();
$this->selectedFeature = $feature;
@@ -424,21 +520,23 @@ class ProjectMap extends Component
$ins = Inspection::where('project_id', $this->project->id)
->with(['feature.layer.phase', 'template', 'user', 'media'])
->find($id);
if (!$ins) return;
if (! $ins) {
return;
}
$this->viewingInspection = [
'id' => $ins->id,
'feature_name' => $ins->feature?->name ?? '—',
'layer_name' => $ins->feature?->layer?->name ?? '—',
'phase_name' => $ins->feature?->layer?->phase?->name ?? '—',
'id' => $ins->id,
'feature_name' => $ins->feature?->name ?? '—',
'layer_name' => $ins->feature?->layer?->name ?? '—',
'phase_name' => $ins->feature?->layer?->phase?->name ?? '—',
'template_name' => $ins->template?->name ?? '—',
'user_name' => $ins->user?->name ?? '—',
'date' => $ins->created_at->format('d/m/Y H:i'),
'status' => $ins->status,
'result' => $ins->result,
'notes' => $ins->notes,
'data' => $ins->data ?? [],
'fields' => $ins->template?->fields ?? [],
'photos' => $ins->media->map(fn ($m) => ['url' => $m->url, 'name' => $m->name, 'id' => $m->id])->values()->all(),
'user_name' => $ins->user?->name ?? '—',
'date' => $ins->created_at->format('d/m/Y H:i'),
'status' => $ins->status,
'result' => $ins->result,
'notes' => $ins->notes,
'data' => $ins->data ?? [],
'fields' => $ins->template?->fields ?? [],
'photos' => $ins->media->map(fn ($m) => ['url' => $m->url, 'name' => $m->name, 'id' => $m->id])->values()->all(),
];
}
@@ -455,7 +553,9 @@ class ProjectMap extends Component
$ins = Inspection::where('project_id', $this->project->id)
->with(['feature.layer.phase', 'template', 'user', 'media'])
->find($id);
if (!$ins) return;
if (! $ins) {
return;
}
$this->editingInspection = $ins;
$this->editInspectionFormData = $ins->data ?? [];
@@ -480,11 +580,13 @@ class ProjectMap extends Component
public function deleteEditPhoto($mediaIndex)
{
if (!$this->editingInspection) return;
if (! $this->editingInspection) {
return;
}
$media = $this->editingInspection->media;
if (isset($media[$mediaIndex])) {
$m = $media[$mediaIndex];
if (!in_array($m->id, $this->editInspectionPhotosToDelete)) {
if (! in_array($m->id, $this->editInspectionPhotosToDelete)) {
$this->editInspectionPhotosToDelete[] = $m->id;
}
}
@@ -492,34 +594,40 @@ class ProjectMap extends Component
public function saveEditInspection()
{
if (!$this->editingInspection) return;
if (! $this->editingInspection) {
return;
}
// Verificar permiso
if (!auth()->user()->can('edit inspections')) {
if (! auth()->user()->can('edit inspections')) {
$this->dispatch('notify', 'Sin permisos para editar inspecciones.');
return;
}
$this->validate([
'selectedTemplateId' => 'required|exists:inspection_templates,id',
'editInspectionPhotos.*' => 'nullable|image|mimes:jpeg,png,jpg,webp|max:10240',
'selectedTemplateId' => 'required|exists:inspection_templates,id',
'editInspectionPhotos.*' => 'nullable|image|mimes:jpeg,png,jpg,webp|max:10240',
'editInspectionPhotosToDelete' => 'array',
'editInspectionPhotosToDelete.*' => 'exists:media,id',
]);
$ins = $this->editingInspection;
if ($ins->project_id !== $this->project->id) abort(403);
if ($ins->project_id !== $this->project->id) {
abort(403);
}
$template = InspectionTemplate::find($this->selectedTemplateId);
foreach ($template->fields as $field) {
if (($field['required'] ?? false) && empty($this->editInspectionFormData[$field['name']])) {
$this->dispatch('notify', "El campo {$field['label']} es obligatorio.");
return;
}
}
// Eliminar fotos marcadas
if (!empty($this->editInspectionPhotosToDelete)) {
if (! empty($this->editInspectionPhotosToDelete)) {
$mediaToDelete = Media::whereIn('id', $this->editInspectionPhotosToDelete)
->where('mediable_type', Inspection::class)
->where('mediable_id', $ins->id)
@@ -532,9 +640,9 @@ class ProjectMap extends Component
// Actualizar datos
$ins->update([
'template_id' => $this->selectedTemplateId,
'result' => $this->editInspectionResult ?: null,
'notes' => $this->editInspectionNotes ?: null,
'data' => $this->editInspectionFormData,
'result' => $this->editInspectionResult ?: null,
'notes' => $this->editInspectionNotes ?: null,
'data' => $this->editInspectionFormData,
]);
// Añadir nuevas fotos
@@ -542,14 +650,14 @@ class ProjectMap extends Component
$mime = $photo->getMimeType();
$path = $photo->store("uploads/inspections/{$ins->id}", 'public');
$ins->media()->create([
'name' => $photo->getClientOriginalName(),
'file_path' => $path,
'file_type' => $mime,
'name' => $photo->getClientOriginalName(),
'file_path' => $path,
'file_type' => $mime,
'file_extension' => $photo->getClientOriginalExtension(),
'file_size' => $photo->getSize(),
'category' => str_starts_with($mime, 'image/') ? 'image' : 'document',
'uploaded_by' => auth()->id(),
'uuid' => (string) \Illuminate\Support\Str::uuid(),
'file_size' => $photo->getSize(),
'category' => str_starts_with($mime, 'image/') ? 'image' : 'document',
'uploaded_by' => auth()->id(),
'uuid' => (string) Str::uuid(),
]);
}
@@ -570,19 +678,21 @@ class ProjectMap extends Component
public function deleteInspection($id)
{
\Log::info('deleteInspection: START', ['id' => $id]);
if (!auth()->user()->can('delete inspections')) {
if (! auth()->user()->can('delete inspections')) {
$this->dispatch('notify', 'Sin permisos para eliminar inspecciones.');
\Log::info('deleteInspection: permission denied');
return;
}
$ins = Inspection::where('project_id', $this->project->id)
->with(['feature', 'media'])
->find($id);
if (!$ins) {
if (! $ins) {
\Log::info('deleteInspection: inspection not found', ['id' => $id]);
$this->dispatch('notify', 'Inspección no encontrada');
return;
}
@@ -612,7 +722,7 @@ class ProjectMap extends Component
->where('user_id', '!=', auth()->id())
->get();
foreach ($usersToNotify as $user) {
$user->notify(new \App\Notifications\InspectionDeletedNotification($ins));
$user->notify(new InspectionDeletedNotification($ins));
}
}
@@ -620,21 +730,25 @@ class ProjectMap extends Component
public function toggleFeatureImages()
{
$this->showFeatureImages = !$this->showFeatureImages;
$this->showFeatureImages = ! $this->showFeatureImages;
$this->loadFeatureImageMarkers();
$this->dispatch('featureImagesToggled', $this->showFeatureImages, $this->featureImageMarkers);
}
public function loadFeatureImageMarkers()
{
if (!$this->showFeatureImages) { $this->featureImageMarkers = []; return; }
if (! $this->showFeatureImages) {
$this->featureImageMarkers = [];
return;
}
$markers = [];
foreach ($this->phases as $phase) {
foreach ($phase->layers as $layer) {
foreach ($layer->features as $feature) {
$image = $feature->images->first();
if ($image) {
$geo = $feature->geometry;
$geo = $feature->geometry;
$coords = null;
if ($geo && isset($geo['coordinates'])) {
if ($geo['type'] === 'Point') {
@@ -646,10 +760,10 @@ class ProjectMap extends Component
if ($coords && $coords['lat'] && $coords['lng']) {
$markers[] = [
'feature_id' => $feature->id,
'name' => $feature->name,
'lat' => $coords['lat'],
'lng' => $coords['lng'],
'image_url' => $image->url,
'name' => $feature->name,
'lat' => $coords['lat'],
'lng' => $coords['lng'],
'image_url' => $image->url,
'image_name' => $image->name,
];
}
@@ -662,8 +776,10 @@ class ProjectMap extends Component
public function toggleFullscreen()
{
$this->formFullscreen = !$this->formFullscreen;
if (!$this->formFullscreen) $this->dispatch('mapResize');
$this->formFullscreen = ! $this->formFullscreen;
if (! $this->formFullscreen) {
$this->dispatch('mapResize');
}
}
public function setActiveTab($tab)
@@ -675,7 +791,7 @@ class ProjectMap extends Component
{
return view('livewire.projects.project-map', [
'project' => $this->project,
'phases' => $this->phases,
'phases' => $this->phases,
]);
}
}
+64 -60
View File
@@ -2,11 +2,11 @@
namespace App\Livewire\Projects;
use Rappasoft\LaravelLivewireTables\DataTableComponent;
use Rappasoft\LaravelLivewireTables\Views\Column;
use App\Models\Project;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Auth;
use App\Models\Project;
use Rappasoft\LaravelLivewireTables\DataTableComponent;
use Rappasoft\LaravelLivewireTables\Views\Column;
class ProjectTable extends DataTableComponent
{
@@ -15,9 +15,9 @@ class ProjectTable extends DataTableComponent
public function configure(): void
{
$this->setPrimaryKey('id')
->setDefaultSort('created_at', 'desc')
->setSortingPillsEnabled(false)
->setAdditionalSelects(['projects.id as id', 'projects.created_at as created_at']);
->setDefaultSort('created_at', 'desc')
->setSortingPillsEnabled(false)
->setAdditionalSelects(['projects.id as id', 'projects.created_at as created_at']);
}
public function builder(): Builder
@@ -30,88 +30,92 @@ class ProjectTable extends DataTableComponent
{
return [
Column::make('Referencia', 'reference')
->sortable()
->searchable()
->format(function ($value, $row) {
$url = route('projects.dashboard', $row->id);
return $value
? '<a href="'.$url.'" class="font-mono text-xs text-primary hover:underline" wire:navigate>'.e($value).'</a>'
: '<span class="text-gray-300">—</span>';
})
->html(),
->sortable()
->searchable()
->format(function ($value, $row) {
$url = route('projects.dashboard', $row->id);
return $value
? '<a href="'.$url.'" class="font-mono text-xs text-primary hover:underline" wire:navigate>'.e($value).'</a>'
: '<span class="text-gray-300">—</span>';
})
->html(),
Column::make(__('Name'), 'name')
->sortable()
->searchable(),
->sortable()
->searchable(),
Column::make(__('Address'), 'address')
->sortable()
->searchable()
->format(fn ($value) => $value
? '<span class="truncate block max-w-xs" title="'.e($value).'">'.e($value).'</span>'
: '<span class="text-gray-400">—</span>')
->html(),
->sortable()
->searchable()
->format(fn ($value) => $value
? '<span class="truncate block max-w-xs" title="'.e($value).'">'.e($value).'</span>'
: '<span class="text-gray-400">—</span>')
->html(),
Column::make(__('Status'), 'status')
->sortable()
->format(function ($value) {
$map = [
'planning' => ['badge-ghost', 'Planificación'],
'in_progress' => ['badge-primary', 'En progreso'],
'paused' => ['badge-warning', 'Pausado'],
'completed' => ['badge-success', 'Completado'],
];
[$cls, $label] = $map[$value] ?? ['badge-ghost', ucfirst($value)];
return '<span class="badge '.$cls.'">'.$label.'</span>';
})
->html(),
->sortable()
->format(function ($value) {
$map = [
'planning' => ['badge-ghost', 'Planificación'],
'in_progress' => ['badge-primary', 'En progreso'],
'paused' => ['badge-warning', 'Pausado'],
'completed' => ['badge-success', 'Completado'],
];
[$cls, $label] = $map[$value] ?? ['badge-ghost', ucfirst($value)];
return '<span class="badge '.$cls.'">'.$label.'</span>';
})
->html(),
Column::make(__('Progress'))
->label(function ($row) {
$avg = $row->phases->avg('progress_percent') ?? 0;
$pct = round($avg);
return '
->label(function ($row) {
$avg = $row->phases->avg('progress_percent') ?? 0;
$pct = round($avg);
return '
<div class="flex items-center gap-2 min-w-[100px]">
<div class="flex-1 bg-gray-200 rounded-full h-2">
<div class="bg-primary h-2 rounded-full" style="width:'.$pct.'%"></div>
</div>
<span class="text-xs text-gray-500 w-8 text-right">'.$pct.'%</span>
</div>';
})
->html(),
})
->html(),
Column::make(__('Start Date'), 'start_date')
->sortable()
->format(fn ($value) => $value ? $value->format('d/m/Y') : '—'),
->sortable()
->format(fn ($value) => $value ? $value->format('d/m/Y') : '—'),
Column::make(__('Est. End'), 'end_date_estimated')
->sortable()
->format(fn ($value) => $value ? $value->format('d/m/Y') : '—'),
->sortable()
->format(fn ($value) => $value ? $value->format('d/m/Y') : '—'),
Column::make(__('Actions'))
->label(function ($row) {
$dashboard = route('projects.dashboard', $row->id);
$map = route('projects.map', $row->id);
$edit = route('projects.edit', $row->id);
->label(function ($row) {
$dashboard = route('projects.dashboard', $row->id);
$map = route('projects.map', $row->id);
$edit = route('projects.edit', $row->id);
$canEdit = Auth::user()->can('edit projects');
$canEdit = Auth::user()->can('edit projects');
$html = '<div class="flex items-center gap-1">';
$html .= '<a href="'.$dashboard.'" class="btn btn-xs btn-outline" title="Dashboard" wire:navigate>
$html = '<div class="flex items-center gap-1">';
$html .= '<a href="'.$dashboard.'" class="btn btn-xs btn-outline" title="Dashboard" wire:navigate>
<svg xmlns="http://www.w3.org/2000/svg" class="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 6a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2H6a2 2 0 01-2-2V6zm10 0a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2h-2a2 2 0 01-2-2V6zM4 16a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2H6a2 2 0 01-2-2v-2zm10 0a2 2 0 012-2h2a2 2 0 012 2v2a2 2 0 01-2 2h-2a2 2 0 01-2-2v-2z"/></svg>
</a>';
$html .= '<a href="'.$map.'" class="btn btn-xs btn-outline" title="Mapa" wire:navigate>
$html .= '<a href="'.$map.'" class="btn btn-xs btn-outline" title="Mapa" wire:navigate>
<svg xmlns="http://www.w3.org/2000/svg" class="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 20l-5.447-2.724A1 1 0 013 16.382V5.618a1 1 0 011.447-.894L9 7m0 13l6-3m-6 3V7m6 10l4.553 2.276A1 1 0 0021 18.382V7.618a1 1 0 00-.553-.894L15 4m0 13V4m0 0L9 7"/></svg>
</a>';
if ($canEdit) {
$html .= '<a href="'.$edit.'" class="btn btn-xs btn-warning" title="Editar" wire:navigate>
if ($canEdit) {
$html .= '<a href="'.$edit.'" class="btn btn-xs btn-warning" title="Editar" wire:navigate>
<svg xmlns="http://www.w3.org/2000/svg" class="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M11 5H6a2 2 0 00-2 2v11a2 2 0 002 2h11a2 2 0 002-2v-5m-1.414-9.414a2 2 0 112.828 2.828L11.828 15H9v-2.828l8.586-8.586z"/></svg>
</a>';
}
$html .= '</div>';
return $html;
})
->html(),
}
$html .= '</div>';
return $html;
})
->html(),
];
}
@@ -12,7 +12,9 @@ use Livewire\Component;
class ProjectTemplatesPicker extends Component
{
public Project $project;
public array $assignedIds = [];
public string $search = '';
public function mount(Project $project)
@@ -41,7 +43,7 @@ class ProjectTemplatesPicker extends Component
public function render()
{
$templates = InspectionTemplate::query()
->when($this->search !== '', fn ($q) => $q->where('name', 'like', '%' . $this->search . '%'))
->when($this->search !== '', fn ($q) => $q->where('name', 'like', '%'.$this->search.'%'))
->orderBy('name')->get();
return view('livewire.projects.project-templates-picker', [
+4 -1
View File
@@ -11,8 +11,11 @@ use Livewire\Component;
class ProjectUsers extends Component
{
public Project $project;
public $allUsers = [];
public $selectedUserId = '';
public $selectedRole = 'viewer';
public function mount(Project $project)
@@ -41,7 +44,7 @@ class ProjectUsers extends Component
$this->validate([
'selectedUserId' => 'required|exists:users,id',
'selectedRole' => 'required|in:' . implode(',', array_keys(ProjectUsersTable::ROLES)),
'selectedRole' => 'required|in:'.implode(',', array_keys(ProjectUsersTable::ROLES)),
]);
$this->project->users()->attach($this->selectedUserId, [
+39 -35
View File
@@ -2,6 +2,7 @@
namespace App\Livewire\Projects;
use App\Models\Project;
use App\Models\User;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Auth;
@@ -20,16 +21,16 @@ class ProjectUsersTable extends DataTableComponent
public const ROLES = [
'supervisor' => 'Supervisor',
'consultant' => 'Consultor',
'client' => 'Cliente',
'viewer' => 'Observador',
'client' => 'Cliente',
'viewer' => 'Observador',
];
public function configure(): void
{
$this->setPrimaryKey('id')
->setDefaultSort('users.name', 'asc')
->setSortingPillsEnabled(false)
->setAdditionalSelects(['users.id as id', 'project_user.role_in_project as role_in_project']);
->setDefaultSort('users.name', 'asc')
->setSortingPillsEnabled(false)
->setAdditionalSelects(['users.id as id', 'project_user.role_in_project as role_in_project']);
}
#[On('project-users-changed')]
@@ -49,48 +50,51 @@ class ProjectUsersTable extends DataTableComponent
{
return [
Column::make('Nombre', 'name')
->sortable()
->searchable()
->format(function ($value, $row) {
$initial = strtoupper(mb_substr($value ?? '?', 0, 1));
return '<div class="flex items-center gap-2">
->sortable()
->searchable()
->format(function ($value, $row) {
$initial = strtoupper(mb_substr($value ?? '?', 0, 1));
return '<div class="flex items-center gap-2">
<span class="w-7 h-7 rounded-full bg-primary text-primary-content flex items-center justify-center text-xs font-bold shrink-0">'.$initial.'</span>
<span class="font-medium">'.e($value).'</span>
</div>';
})
->html(),
})
->html(),
Column::make('Email', 'email')
->sortable()
->searchable(),
->sortable()
->searchable(),
Column::make('Rol', 'role_in_project')
->label(function ($row) {
$current = $row->role_in_project;
if (! Auth::user()->can('assign users')) {
return '<span class="badge badge-sm">'.(self::ROLES[$current] ?? ucfirst((string) $current)).'</span>';
}
$opts = '';
foreach (self::ROLES as $val => $label) {
$opts .= '<option value="'.$val.'"'.($current === $val ? ' selected' : '').'>'.$label.'</option>';
}
return '<select wire:change="changeRole('.$row->id.', $event.target.value)" class="select select-bordered select-xs">'.$opts.'</select>';
})
->html(),
->label(function ($row) {
$current = $row->role_in_project;
if (! Auth::user()->can('assign users')) {
return '<span class="badge badge-sm">'.(self::ROLES[$current] ?? ucfirst((string) $current)).'</span>';
}
$opts = '';
foreach (self::ROLES as $val => $label) {
$opts .= '<option value="'.$val.'"'.($current === $val ? ' selected' : '').'>'.$label.'</option>';
}
return '<select wire:change="changeRole('.$row->id.', $event.target.value)" class="select select-bordered select-xs">'.$opts.'</select>';
})
->html(),
Column::make('Acciones')
->label(function ($row) {
if (! Auth::user()->can('assign users')) {
return '';
}
return '<div class="flex justify-end">
->label(function ($row) {
if (! Auth::user()->can('assign users')) {
return '';
}
return '<div class="flex justify-end">
<button wire:click="removeUser('.$row->id.')" wire:confirm="¿Quitar a '.e($row->name).' del proyecto?"
class="btn btn-xs btn-error btn-outline" title="Quitar del proyecto">
<svg xmlns="http://www.w3.org/2000/svg" class="w-3.5 h-3.5" fill="none" viewBox="0 0 24 24" stroke="currentColor"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12"/></svg>
</button>
</div>';
})
->html(),
})
->html(),
];
}
@@ -109,7 +113,7 @@ class ProjectUsersTable extends DataTableComponent
if (! array_key_exists($role, self::ROLES)) {
return;
}
\App\Models\Project::findOrFail($this->projectId)
Project::findOrFail($this->projectId)
->users()->updateExistingPivot($userId, ['role_in_project' => $role]);
$this->dispatch('project-users-changed');
$this->dispatch('notify', 'Rol actualizado.');
@@ -118,7 +122,7 @@ class ProjectUsersTable extends DataTableComponent
public function removeUser($userId): void
{
abort_unless(Auth::user()->can('assign users'), 403);
\App\Models\Project::findOrFail($this->projectId)->users()->detach($userId);
Project::findOrFail($this->projectId)->users()->detach($userId);
$this->dispatch('project-users-changed');
$this->dispatch('notify', 'Usuario eliminado del proyecto.');
}