Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- namespace App\Filament\Jury\Pages;
- use Filament\Forms\Form;
- use Filament\Pages\Page;
- use Filament\Facades\Filament;
- use Illuminate\Support\Facades\Auth;
- use App\Models\Team;
- use App\Models\TeamScore;
- use App\Models\ScoringCategory;
- use Filament\Forms\Contracts\HasForms;
- use Filament\Forms\Concerns\InteractsWithForms;
- use Filament\Notifications\Notification;
- use Illuminate\Support\Facades\Log;
- use JaOcero\RadioDeck\Forms\Components\RadioDeck;
- class Scoring extends Page implements HasForms
- {
- use InteractsWithForms;
- protected static ?string $navigationIcon = 'heroicon-o-trophy';
- protected static ?string $navigationLabel = 'Team Scoring';
- protected static ?string $title = 'Team Scoring';
- protected static string $view = 'filament.jury.pages.scoring';
- public ?Team $currentTeam = null;
- public array $scores = [];
- protected $listeners = ['fillScore'];
- public function mount(): void
- {
- $event = Filament::getTenant();
- $this->currentTeam = $event ? Team::find($event->current_team_id) : null;
- // Load initial scores from DB
- $this->fillScore();
- }
- public function form(Form $form): Form
- {
- return $form->schema($this->getFormSchema())->statePath('scores');
- }
- protected function getFormSchema(): array
- {
- if (!$this->currentTeam) {
- return $this->noActiveTeamMessage();
- }
- if (!$this->hasUnscoredSubcategories()) {
- return $this->completedScoringMessage();
- }
- return $this->generateScoringForm();
- }
- public function save(): void
- {
- $juryId = Auth::id();
- $data = $this->form->getState();
- foreach ($data as $subcategoryId => $score) {
- TeamScore::updateOrCreate(
- [
- 'team_id' => $this->currentTeam->id,
- 'judge_id' => $juryId,
- 'subcategory_id' => $subcategoryId
- ],
- ['score' => $score]
- );
- }
- Notification::make()
- ->title('Scoring Saved')
- ->body('All scores have been successfully updated.')
- ->success()
- ->send();
- $this->dispatch('fillScore');
- }
- public function updateScore($subcategoryId, $score): void
- {
- $juryId = Auth::id();
- // Update score in DB
- TeamScore::updateOrCreate(
- [
- 'team_id' => $this->currentTeam->id,
- 'judge_id' => $juryId,
- 'subcategory_id' => $subcategoryId
- ],
- ['score' => $score]
- );
- // ✅ Update only the changed value in the scores array
- $this->scores[$subcategoryId] = $score;
- Notification::make()
- ->info()
- ->title('Score Updated')
- ->body("Subcategory {$subcategoryId}: {$score}")
- ->send();
- }
- public function fillScore()
- {
- if (!$this->currentTeam) {
- return;
- }
- // Retrieve scores from the database
- $this->scores = TeamScore::where([
- 'team_id' => $this->currentTeam->id,
- 'judge_id' => Auth::id(),
- ])->pluck('score', 'subcategory_id')->toArray();
- Log::info('Loaded scores:', $this->scores);
- // ✅ Explicitly update each radio button state using `set()`
- foreach ($this->scores as $subcategoryId => $score) {
- $this->form->getComponent("scores.{$subcategoryId}")?->state($score);
- }
- // ✅ Fill the form with scores to ensure UI updates
- $this->form->fill($this->scores);
- }
- private function noActiveTeamMessage(): array
- {
- return [
- \Filament\Forms\Components\Section::make('Informasi')
- ->description('Tidak ada tim yang sedang bertanding saat ini.')
- ->schema([]),
- ];
- }
- private function completedScoringMessage(): array
- {
- return [
- \Filament\Forms\Components\Section::make('Informasi')
- ->description('Anda telah menyelesaikan penilaian untuk tim ini.')
- ->schema([]),
- ];
- }
- private function hasUnscoredSubcategories(): bool
- {
- return TeamScore::where([
- 'team_id' => $this->currentTeam->id,
- 'judge_id' => Auth::id(),
- ])->whereNull('score')->exists();
- }
- private function generateScoringForm(): array
- {
- $event = Filament::getTenant();
- $categories = ScoringCategory::where('event_id', $event->id)->get();
- $formSchema = [];
- foreach ($categories as $category) {
- $subcategories = $category->scoringSubcategories()->where('event_id', $event->id)->get();
- $fields = [];
- foreach ($subcategories as $subcategory) {
- $scoreOptions = \App\Enums\ScoreOption::generate(
- $subcategory->starting_point,
- $subcategory->step,
- $event->range
- );
- $subcategoryId = $subcategory->id;
- $defaultScore = $this->scores[$subcategoryId] ?? null; // Ensure the score is retrieved
- Log::info("Setting default score for Subcategory {$subcategoryId}: " . json_encode($defaultScore));
- $fields[] = RadioDeck::make("scores.{$subcategoryId}")
- ->label($subcategory->name)
- ->options(\App\Enums\ScoreOption::generate(
- $subcategory->starting_point,
- $subcategory->step,
- $event->range
- ))
- ->columns(13)
- ->live()
- ->afterStateUpdated(fn($state) => $this->updateScore($subcategoryId, $state))
- ->default($defaultScore)
- ->padding('p-4')
- ->extraCardsAttributes([
- 'class' => 'rounded-xl hover:bg-gray-200 transition-all duration-150 peer-checked:bg-gray-200',
- ])
- ->extraOptionsAttributes([
- 'class' => 'leading-none w-full flex flex-col items-center justify-center',
- ])
- ->color('gray')
- ->required();
- }
- $formSchema[] = \Filament\Forms\Components\Section::make($category->name)
- ->schema($fields);
- }
- return $formSchema;
- }
- protected function getFormActions(): array
- {
- return [
- \Filament\Actions\Action::make('save')
- ->label(__('filament-panels::resources/pages/edit-record.form.actions.save.label'))
- ->submit('save'),
- ];
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement