auditionadmin/app/Actions/Tabulation/EnterBonusScore.php

81 lines
2.6 KiB
PHP

<?php
/** @noinspection PhpUnhandledExceptionInspection */
namespace App\Actions\Tabulation;
use App\Exceptions\ScoreEntryException;
use App\Models\BonusScore;
use App\Models\Entry;
use App\Models\User;
use Illuminate\Database\Eloquent\Collection;
use Illuminate\Support\Facades\App;
class EnterBonusScore
{
public function __construct()
{
}
public function __invoke(User $judge, Entry $entry, int $score): void
{
$getRelatedEntries = App::make(GetBonusScoreRelatedEntries::class);
$this->basicValidations($judge, $entry);
$this->validateJudgeValidity($judge, $entry, $score);
$entries = $getRelatedEntries($entry);
// Create the score for each related entry
foreach ($entries as $relatedEntry) {
// Also delete any cached scores
BonusScore::create([
'entry_id' => $relatedEntry->id,
'user_id' => $judge->id,
'originally_scored_entry' => $entry->id,
'score' => $score,
]);
}
}
protected function getRelatedEntries(Entry $entry): Collection
{
$bonusScore = $entry->audition->bonusScore->first();
$relatedAuditions = $bonusScore->auditions;
// Get all entries that have a student_id equal to that of entry and an audition_id in the related auditions
return Entry::where('student_id', $entry->student_id)
->whereIn('audition_id', $relatedAuditions->pluck('id'))
->get();
}
protected function basicValidations(User $judge, Entry $entry): void
{
if (! $judge->exists) {
throw new ScoreEntryException('Invalid judge provided');
}
if (! $entry->exists) {
throw new ScoreEntryException('Invalid entry provided');
}
if ($entry->audition->bonusScore->count() === 0) {
throw new ScoreEntryException('Entry does not have a bonus score');
}
}
protected function validateJudgeValidity(User $judge, Entry $entry, $score): void
{
if (BonusScore::where('entry_id', $entry->id)->where('user_id', $judge->id)->exists()) {
throw new ScoreEntryException('That judge has already scored that entry');
}
$bonusScore = $entry->audition->bonusScore->first();
if (! $bonusScore->judges->contains($judge)) {
throw new ScoreEntryException('That judge is not assigned to judge that bonus score');
}
if ($score > $bonusScore->max_score) {
throw new ScoreEntryException('That score exceeds the maximum');
}
}
}