Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions app/Console/Commands/SyncEndorsementActivities.php
Original file line number Diff line number Diff line change
Expand Up @@ -156,6 +156,9 @@ protected function updateEndorsementActivity(EndorsementActivity $endorsementAct
}
}

$eligibleSince = $this->activityService->calculateEligibleSince($endorsementData);
$endorsementActivity->eligible_since = $eligibleSince;

$endorsementActivity->save();

} catch (\Exception $e) {
Expand Down
2 changes: 2 additions & 0 deletions app/Http/Controllers/EndorsementController.php
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,7 @@ public function mentorView(Request $request): Response
'activityHours' => $activity->activity_hours,
'status' => $activity->status,
'progress' => $activity->progress,
'eligibleSince' => $activity->eligible_since,
'removalDate' => $activity->removal_date?->format('Y-m-d'),
'removalDays' => $activity->removal_date
? $activity->removal_date->diffInDays(now(), false)
Expand Down Expand Up @@ -305,6 +306,7 @@ public function mentorView(Request $request): Response
'userPermissions' => [
'canRemoveForPositions' => $canRemovePositions,
'canRemoveAny' => ($user->is_superuser || $user->is_admin) || (!empty($canRemovePositions) && count($canRemovePositions) > 0),
'isAdmin' => $user->is_superuser || $user->is_admin,
],
]);
}
Expand Down
2 changes: 2 additions & 0 deletions app/Models/EndorsementActivity.php
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ class EndorsementActivity extends Model
'last_updated',
'last_activity_date',
'removal_date',
'eligible_since',
'removal_notified',
'created_at_vateud',
];
Expand All @@ -27,6 +28,7 @@ class EndorsementActivity extends Model
'last_updated' => 'datetime',
'last_activity_date' => 'date',
'removal_date' => 'date',
'eligible_since' => 'datetime',
'removal_notified' => 'boolean',
'created_at_vateud' => 'datetime',
];
Expand Down
173 changes: 173 additions & 0 deletions app/Services/VatsimActivityService.php
Original file line number Diff line number Diff line change
Expand Up @@ -280,4 +280,177 @@ public function getActivityProgress(float $activityMinutes): float
$minRequiredMinutes = config('services.vateud.min_activity_minutes', 180);
return min(($activityMinutes / $minRequiredMinutes) * 100, 100);
}

protected function getVatsimConnectionsTwoYears(int $vatsimId): array
{
$cacheKey = "vatsim_activity_2y:{$vatsimId}";

return Cache::remember($cacheKey, now()->addHours(6), function () use ($vatsimId) {
$start = Carbon::now()->subYears(2)->format('Y-m-d');
$apiUrl = "http://stats.vatsim-germany.org/api/atc/{$vatsimId}/sessions/?start_date={$start}";

try {
$response = Http::timeout(15)
->retry(2, 1000)
->get($apiUrl);

if (!$response->successful()) {
return [];
}

$data = $response->json();
return is_array($data) ? $data : [];

} catch (\Exception $e) {
Log::error('Error fetching 2y VATSIM connections', [
'vatsim_id' => $vatsimId,
'error' => $e->getMessage(),
]);
return [];
}
});
}

protected function extractRelevantSessions(array $endorsement, array $connections): array
{
$sessions = [];
$position = $endorsement['position'];
$inTransition = Carbon::now()->lessThan(Carbon::parse($this->transitionEndDate));

foreach ($connections as $connection) {
$callsign = $connection['callsign'] ?? '';
$minutes = floatval($connection['minutes_online'] ?? 0);
$date = $this->parseConnectionDate($connection);

if (!$date || $minutes <= 0) {
continue;
}

$matches = false;

if (str_ends_with($position, '_CTR')) {
$ctrlPrefix = substr($position, 0, 6);

if (str_starts_with($callsign, $ctrlPrefix) ||
($position === 'EDWW_W_CTR' && $callsign === 'EDWW_CTR')) {
$matches = true;
}
} else {
$parts = explode('_', $position);
if (count($parts) >= 2) {
$airport = $parts[0];
$station = end($parts);

$ctrStations = $this->ctrTopdown[$airport] ?? [];
$legacyCtrStations = $inTransition ? ($this->legacyCtrTopdown[$airport] ?? []) : [];
$appStations = $this->appTopdown[$airport] ?? [];

$matchesSuffix = $this->suffixCondition($airport, $station, $callsign);

$matchesCtr = false;

$ctrAllowedStations = ['APP', 'TWR', 'GNDDEL'];

if (in_array($station, $ctrAllowedStations, true)) {
$allCtrStations = array_unique(array_merge($ctrStations, $legacyCtrStations));

foreach ($allCtrStations as $ctrStation) {
if (str_starts_with($callsign, $ctrStation)) {
$matchesCtr = true;
break;
}
}

if (!$matchesCtr && $station !== 'APP') {
foreach ($appStations as $appStation) {
if (str_starts_with($callsign, $appStation)) {
$matchesCtr = true;
break;
}
}
}
}

if (!$matchesCtr && $station === 'APP') {
foreach ($appStations as $appStation) {
if (str_starts_with($callsign, $appStation)) {
$matchesCtr = true;
break;
}
}
}

$matches = $matchesCtr || $matchesSuffix;
}
}

if ($matches) {
$sessions[] = [
'date' => $date,
'minutes' => $minutes,
];
}
}

usort($sessions, fn($a, $b) => $a['date']->lt($b['date']) ? -1 : 1);

return $sessions;
}

public function calculateEligibleSince(array $endorsement): ?Carbon
{
$connections = $this->getVatsimConnectionsTwoYears($endorsement['user_cid']);
$sessions = $this->extractRelevantSessions($endorsement, $connections);

// No sessions in 2 years -> no value
if (empty($sessions)) {
return null;
}

$requiredMinutes = config('services.vateud.min_activity_minutes', 180);

$events = [];

foreach ($sessions as $session) {
$events[] = [
'date' => $session['date']->copy(),
'delta' => $session['minutes'],
];

$events[] = [
'date' => $session['date']->copy()->addDays(180),
'delta' => -$session['minutes'],
];
}

usort($events, function ($a, $b) {
return $a['date']->timestamp <=> $b['date']->timestamp;
});

$runningMinutes = 0;
$eligibleSince = null;

foreach ($events as $event) {
$before = $runningMinutes;

$runningMinutes += $event['delta'];

if (
$before >= $requiredMinutes &&
$runningMinutes < $requiredMinutes
) {
$eligibleSince = $event['date']->copy();
}

if ($runningMinutes >= $requiredMinutes) {
$eligibleSince = null;
}
}

if ($runningMinutes < $requiredMinutes) {
return $eligibleSince;
}

return null;
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;
use Illuminate\Support\Facades\Schema;

return new class extends Migration
{
/**
* Run the migrations.
*/
public function up(): void
{
Schema::table('endorsement_activities', function (Blueprint $table) {
$table->timestamp('eligible_since')
->nullable()
->after('removal_date');
});
}

/**
* Reverse the migrations.
*/
public function down(): void
{
Schema::table('endorsement_activities', function (Blueprint $table) {
$table->dropColumn('eligible_since');
});
}
};
Loading