77 lines
2.5 KiB
PHP
77 lines
2.5 KiB
PHP
<?php
|
|
|
|
namespace App\Http\Controllers;
|
|
|
|
use App\Support\DashboardSchedule;
|
|
use Illuminate\Http\RedirectResponse;
|
|
use Illuminate\Http\Request;
|
|
use Illuminate\Support\Facades\Artisan;
|
|
use Illuminate\Support\Facades\Log;
|
|
use Illuminate\Support\Str;
|
|
use Illuminate\Validation\Rule;
|
|
use Throwable;
|
|
|
|
class ScheduleSettingsController extends Controller
|
|
{
|
|
public function update(Request $request): RedirectResponse
|
|
{
|
|
abort_unless($request->user()->role === 'admin', 403);
|
|
|
|
$jobKeys = array_keys(DashboardSchedule::jobs());
|
|
$frequencyKeys = array_keys(DashboardSchedule::frequencyOptions());
|
|
|
|
$validated = $request->validate([
|
|
'schedules' => ['required', 'array:'.implode(',', $jobKeys)],
|
|
'schedules.*' => ['required', 'string', Rule::in($frequencyKeys)],
|
|
]);
|
|
|
|
$frequencies = collect($validated['schedules'])
|
|
->only($jobKeys)
|
|
->all();
|
|
|
|
DashboardSchedule::persistRuntimeFrequencies($frequencies);
|
|
|
|
return redirect()
|
|
->route('settings.index')
|
|
->with('status', 'Schedule settings saved. Laravel will apply them on the next scheduler tick.');
|
|
}
|
|
|
|
public function run(Request $request, string $job): RedirectResponse
|
|
{
|
|
abort_unless($request->user()->role === 'admin', 403);
|
|
|
|
$definition = DashboardSchedule::jobs()[$job] ?? null;
|
|
|
|
abort_unless($definition !== null && ($definition['manual'] ?? false) === true, 404);
|
|
|
|
$command = $definition['command'] ?? null;
|
|
|
|
abort_unless(is_string($command) && $command !== '', 404);
|
|
|
|
try {
|
|
$exitCode = Artisan::call($command);
|
|
$output = Str::limit(trim(preg_replace('/\s+/', ' ', Artisan::output()) ?? ''), 220);
|
|
} catch (Throwable $exception) {
|
|
Log::warning('Manual scheduled job failed.', [
|
|
'job' => $job,
|
|
'command' => $command,
|
|
'error' => $exception->getMessage(),
|
|
]);
|
|
|
|
return redirect()
|
|
->route('settings.index')
|
|
->withErrors(['schedule' => $definition['name'].' failed: '.$exception->getMessage()]);
|
|
}
|
|
|
|
if ($exitCode !== 0) {
|
|
return redirect()
|
|
->route('settings.index')
|
|
->withErrors(['schedule' => $definition['name'].' finished with exit code '.$exitCode.'. '.$output]);
|
|
}
|
|
|
|
return redirect()
|
|
->route('settings.index')
|
|
->with('status', $definition['name'].' completed.'.($output !== '' ? ' '.$output : ''));
|
|
}
|
|
}
|