104 lines
3.1 KiB
PHP
104 lines
3.1 KiB
PHP
<?php
|
|
|
|
namespace App\Models;
|
|
|
|
use Illuminate\Database\Eloquent\Model;
|
|
use Illuminate\Database\Eloquent\Relations\BelongsTo;
|
|
use Illuminate\Support\Collection;
|
|
|
|
class Doubler extends Model
|
|
{
|
|
// Specify that we're not using a single primary key
|
|
protected $primaryKey = null;
|
|
|
|
public $incrementing = false;
|
|
|
|
protected $guarded = [];
|
|
|
|
protected $casts = [
|
|
'entries' => 'array',
|
|
];
|
|
|
|
public function student(): BelongsTo
|
|
{
|
|
return $this->belongsTo(Student::class);
|
|
}
|
|
|
|
public function event(): BelongsTo
|
|
{
|
|
return $this->belongsTo(Event::class);
|
|
}
|
|
|
|
public function entries(): Collection
|
|
{
|
|
return Entry::whereIn('id', $this->entries)->get();
|
|
}
|
|
|
|
// Find a doubler based on both keys
|
|
public static function findDoubler($studentId, $eventId)
|
|
{
|
|
return static::where('student_id', $studentId)
|
|
->where('event_id', $eventId)
|
|
->first();
|
|
}
|
|
|
|
/**
|
|
* Sync doubler records for a specified event
|
|
*/
|
|
public static function syncForEvent($eventId): void
|
|
{
|
|
|
|
if ($eventId instanceof Event) {
|
|
$eventId = $eventId->id;
|
|
}
|
|
|
|
// Get students with multiple entries in this event's auditions
|
|
$studentsWithMultipleEntries = Student::query()
|
|
->select('students.id')
|
|
->join('entries', 'students.id', '=', 'entries.student_id')
|
|
->join('auditions', 'entries.audition_id', '=', 'auditions.id')
|
|
->where('auditions.event_id', $eventId)
|
|
->groupBy('students.id')
|
|
->havingRaw('COUNT(entries.id) > 1')
|
|
->with('entries')
|
|
->get();
|
|
|
|
foreach ($studentsWithMultipleEntries as $student) {
|
|
// Get entries that are not declined. If only one, they're our accepted entry.
|
|
$entryList = collect(); // List of entry ids for th is student in this event
|
|
$undecidedEntries = collect(); // List of entry ids that are not declined, no-show, or failed prelim
|
|
$entryList = $student->entriesForEvent($eventId)->pluck('id');
|
|
$undecidedEntries = $student->entriesForEvent($eventId)
|
|
->whereDoesntHave('flags', function ($query) {
|
|
$query->whereIn('flag_name', ['declined', 'no-show', 'failed-prelim']);
|
|
})
|
|
->pluck('id');
|
|
|
|
// Create or update the doubler record
|
|
static::updateOrCreate(
|
|
[
|
|
'student_id' => $student->id,
|
|
'event_id' => $eventId,
|
|
],
|
|
[
|
|
'entries' => $entryList,
|
|
'accepted_entry' => $acceptedEntryId,
|
|
]
|
|
);
|
|
}
|
|
|
|
// remove doubler records for students who no longer have multiple entries
|
|
static::where('event_id', $eventId)
|
|
->whereNotIn('student_id', $studentsWithMultipleEntries->pluck('id'))
|
|
->delete();
|
|
}
|
|
|
|
public static function syncDoublers(): void
|
|
{
|
|
$events = Event::all();
|
|
foreach ($events as $event) {
|
|
static::syncForEvent($event);
|
|
}
|
|
}
|
|
}
|