Advertisement
Guest User

Scoring.php (updated)

a guest
Feb 3rd, 2025
19
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 6.88 KB | None | 0 0
  1. <?php
  2.  
  3. namespace App\Filament\Jury\Pages;
  4.  
  5. use Filament\Forms\Form;
  6. use Filament\Pages\Page;
  7. use Filament\Facades\Filament;
  8. use Illuminate\Support\Facades\Auth;
  9. use App\Models\Team;
  10. use App\Models\TeamScore;
  11. use App\Models\ScoringCategory;
  12. use Filament\Forms\Contracts\HasForms;
  13. use Filament\Forms\Concerns\InteractsWithForms;
  14. use Filament\Notifications\Notification;
  15. use Illuminate\Support\Facades\Log;
  16. use JaOcero\RadioDeck\Forms\Components\RadioDeck;
  17.  
  18. class Scoring extends Page implements HasForms
  19. {
  20.     use InteractsWithForms;
  21.  
  22.     protected static ?string $navigationIcon = 'heroicon-o-trophy';
  23.     protected static ?string $navigationLabel = 'Team Scoring';
  24.     protected static ?string $title = 'Team Scoring';
  25.  
  26.     protected static string $view = 'filament.jury.pages.scoring';
  27.     public ?Team $currentTeam = null;
  28.     public array $scores = [];
  29.  
  30.     protected $listeners = ['fillScore'];
  31.  
  32.     public function mount(): void
  33.     {
  34.         $event = Filament::getTenant();
  35.         $this->currentTeam = $event ? Team::find($event->current_team_id) : null;
  36.  
  37.         // Load initial scores from DB
  38.         $this->fillScore();
  39.     }
  40.  
  41.     public function form(Form $form): Form
  42.     {
  43.         return $form->schema($this->getFormSchema())->statePath('scores');
  44.     }
  45.  
  46.     protected function getFormSchema(): array
  47.     {
  48.         if (!$this->currentTeam) {
  49.             return $this->noActiveTeamMessage();
  50.         }
  51.  
  52.         if (!$this->hasUnscoredSubcategories()) {
  53.             return $this->completedScoringMessage();
  54.         }
  55.  
  56.         return $this->generateScoringForm();
  57.     }
  58.  
  59.     public function save(): void
  60.     {
  61.         $juryId = Auth::id();
  62.         $data = $this->form->getState();
  63.  
  64.         foreach ($data as $subcategoryId => $score) {
  65.             TeamScore::updateOrCreate(
  66.                 [
  67.                     'team_id' => $this->currentTeam->id,
  68.                     'judge_id' => $juryId,
  69.                     'subcategory_id' => $subcategoryId
  70.                 ],
  71.                 ['score' => $score]
  72.             );
  73.         }
  74.  
  75.         Notification::make()
  76.             ->title('Scoring Saved')
  77.             ->body('All scores have been successfully updated.')
  78.             ->success()
  79.             ->send();
  80.  
  81.         $this->dispatch('fillScore');
  82.     }
  83.  
  84.     public function updateScore($subcategoryId, $score): void
  85.     {
  86.         $juryId = Auth::id();
  87.  
  88.         // Update score in DB
  89.         TeamScore::updateOrCreate(
  90.             [
  91.                 'team_id' => $this->currentTeam->id,
  92.                 'judge_id' => $juryId,
  93.                 'subcategory_id' => $subcategoryId
  94.             ],
  95.             ['score' => $score]
  96.         );
  97.  
  98.         // ✅ Update only the changed value in the scores array
  99.         $this->scores[$subcategoryId] = $score;
  100.  
  101.         Notification::make()
  102.             ->info()
  103.             ->title('Score Updated')
  104.             ->body("Subcategory {$subcategoryId}: {$score}")
  105.             ->send();
  106.     }
  107.  
  108.  
  109.  
  110.     public function fillScore()
  111.     {
  112.         if (!$this->currentTeam) {
  113.             return;
  114.         }
  115.  
  116.         // Retrieve scores from the database
  117.         $this->scores = TeamScore::where([
  118.             'team_id' => $this->currentTeam->id,
  119.             'judge_id' => Auth::id(),
  120.         ])->pluck('score', 'subcategory_id')->toArray();
  121.  
  122.         Log::info('Loaded scores:', $this->scores);
  123.  
  124.         // ✅ Explicitly update each radio button state using `set()`
  125.         foreach ($this->scores as $subcategoryId => $score) {
  126.             $this->form->getComponent("scores.{$subcategoryId}")?->state($score);
  127.         }
  128.  
  129.         // ✅ Fill the form with scores to ensure UI updates
  130.         $this->form->fill($this->scores);
  131.     }
  132.  
  133.  
  134.  
  135.  
  136.     private function noActiveTeamMessage(): array
  137.     {
  138.         return [
  139.             \Filament\Forms\Components\Section::make('Informasi')
  140.                 ->description('Tidak ada tim yang sedang bertanding saat ini.')
  141.                 ->schema([]),
  142.         ];
  143.     }
  144.  
  145.     private function completedScoringMessage(): array
  146.     {
  147.         return [
  148.             \Filament\Forms\Components\Section::make('Informasi')
  149.                 ->description('Anda telah menyelesaikan penilaian untuk tim ini.')
  150.                 ->schema([]),
  151.         ];
  152.     }
  153.  
  154.     private function hasUnscoredSubcategories(): bool
  155.     {
  156.         return TeamScore::where([
  157.             'team_id' => $this->currentTeam->id,
  158.             'judge_id' => Auth::id(),
  159.         ])->whereNull('score')->exists();
  160.     }
  161.  
  162.     private function generateScoringForm(): array
  163.     {
  164.         $event = Filament::getTenant();
  165.         $categories = ScoringCategory::where('event_id', $event->id)->get();
  166.         $formSchema = [];
  167.  
  168.         foreach ($categories as $category) {
  169.             $subcategories = $category->scoringSubcategories()->where('event_id', $event->id)->get();
  170.             $fields = [];
  171.  
  172.             foreach ($subcategories as $subcategory) {
  173.                 $scoreOptions = \App\Enums\ScoreOption::generate(
  174.                     $subcategory->starting_point,
  175.                     $subcategory->step,
  176.                     $event->range
  177.                 );
  178.  
  179.                 $subcategoryId = $subcategory->id;
  180.                 $defaultScore = $this->scores[$subcategoryId] ?? null; // Ensure the score is retrieved
  181.  
  182.                 Log::info("Setting default score for Subcategory {$subcategoryId}: " . json_encode($defaultScore));
  183.  
  184.                 $fields[] = RadioDeck::make("scores.{$subcategoryId}")
  185.                     ->label($subcategory->name)
  186.                     ->options(\App\Enums\ScoreOption::generate(
  187.                         $subcategory->starting_point,
  188.                         $subcategory->step,
  189.                         $event->range
  190.                     ))
  191.                     ->columns(13)
  192.                     ->live()
  193.                     ->afterStateUpdated(fn($state) => $this->updateScore($subcategoryId, $state))
  194.                     ->default($defaultScore)
  195.                     ->padding('p-4')
  196.                     ->extraCardsAttributes([
  197.                         'class' => 'rounded-xl hover:bg-gray-200 transition-all duration-150 peer-checked:bg-gray-200',
  198.                     ])
  199.                     ->extraOptionsAttributes([
  200.                         'class' => 'leading-none w-full flex flex-col items-center justify-center',
  201.                     ])
  202.                     ->color('gray')
  203.                     ->required();
  204.             }
  205.  
  206.             $formSchema[] = \Filament\Forms\Components\Section::make($category->name)
  207.                 ->schema($fields);
  208.         }
  209.  
  210.         return $formSchema;
  211.     }
  212.  
  213.  
  214.     protected function getFormActions(): array
  215.     {
  216.         return [
  217.             \Filament\Actions\Action::make('save')
  218.                 ->label(__('filament-panels::resources/pages/edit-record.form.actions.save.label'))
  219.                 ->submit('save'),
  220.         ];
  221.     }
  222. }
  223.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement