preselectedTerritorioId = $territorioId; $this->territorio_id = $territorioId; $this->assigned_at = now()->format('Y-m-d'); } protected function rules(): array { return [ 'territorio_id' => 'required|exists:territori,id', 'proclamatore_id' => 'required|exists:proclamatori,id', 'assigned_at' => 'required|date|before_or_equal:today', ]; } public function save() { $this->validate(); $territorio = Territorio::findOrFail($this->territorio_id); // Check territory is available (not currently assigned) if ($territorio->assegnazioneCorrente) { session()->flash('error', "Il territorio {$territorio->numero} è già assegnato a {$territorio->assegnazioneCorrente->proclamatore->nome_completo}."); return; } // Check territory is active if (!$territorio->attivo) { session()->flash('error', "Il territorio {$territorio->numero} è inattivo."); return; } $proclamatore = Proclamatore::findOrFail($this->proclamatore_id); if (!$proclamatore->attivo) { session()->flash('error', "Il proclamatore {$proclamatore->nome_completo} è inattivo."); return; } $assignedDate = \Carbon\Carbon::parse($this->assigned_at); $annoTeocratico = AnnoTeocratico::perData($assignedDate); $assegnazione = Assegnazione::create([ 'territorio_id' => $this->territorio_id, 'proclamatore_id' => $this->proclamatore_id, 'anno_teocratico_id' => $annoTeocratico->id, 'assigned_at' => $assignedDate, 'created_by' => auth()->id(), ]); activity()->causedBy(auth()->user()) ->performedOn($assegnazione) ->withProperties([ 'territorio' => $territorio->numero, 'proclamatore' => $proclamatore->nome_completo, ]) ->log('assigned'); session()->flash('success', "Territorio {$territorio->numero} assegnato a {$proclamatore->nome_completo}."); return $this->redirect(route('territori.show', $territorio), navigate: true); } #[Computed] public function selectedThumbnailUrl(): ?string { if (!$this->territorio_id) { return null; } $t = Territorio::find($this->territorio_id); return $t?->thumbnail_path ? Storage::url($t->thumbnail_path) : null; } public function render() { $territoriQuery = Territorio::where('attivo', true) ->whereDoesntHave('assegnazioni', fn($q) => $q->aperte()) ->with(['zona', 'tipologia']); if (trim($this->territorioSearch) !== '') { $term = trim($this->territorioSearch); $territoriQuery->where(function ($q) use ($term) { $q->where('numero', 'like', "%{$term}%") ->orWhereHas('zona', fn($z) => $z->where('nome', 'like', "%{$term}%")) ->orWhereHas('tipologia', fn($t) => $t->where('nome', 'like', "%{$term}%")); }); } $territoriDisponibili = $territoriQuery ->orderBy('numero') ->get(); $proclamatoriAttivi = Proclamatore::attivi() ->get() ->sortBy(fn($p) => mb_strtolower($p->cognome . ' ' . $p->nome)); return view('livewire.assegnazioni.assegna', [ 'territoriDisponibili' => $territoriDisponibili, 'proclamatoriAttivi' => $proclamatoriAttivi, ]); } }