Add settings-driven Artisan scheduler registry with Etsy sync and token refresh jobs

Introduces App\Support\DashboardSchedule (modelled on LHITS_Dashboard's
pattern) as a single settings-driven registry for recurring Artisan jobs,
replacing the two hard-coded Schedule::command() lines in
routes/console.php.

Migrated unchanged:
- integrations_refresh (integrations:refresh), every_30_seconds, withoutOverlapping(5)
- alerts_scan (alerts:scan), every_30_seconds, withoutOverlapping(5)

New:
- etsy_sync (etsy:sync), every_15_minutes - forces a fresh pull of Etsy
  receipts/listings into the existing IntegrationCache entries, decoupled
  from the bundled integrations:refresh job so it can be tuned/disabled
  independently of Parcel2Go/BamBuddy/dryer refreshes.
- etsy_token_refresh (etsy:refresh-token), every_45_minutes - proactively
  refreshes the Etsy OAuth token (tokens last ~1hr) via a new public
  Etsy::refreshAccessToken() wrapper around the existing on-demand
  accessToken() refresh logic, so the connection survives quiet periods.

Frequency is persisted to storage/app/dashboard-schedules.json (no
app_settings table exists in this app, unlike LHITS's AppSetting-backed
store) and surfaced in a new 'Scheduler' section on the existing Settings
page (ScheduleSettingsController + routes), with per-job frequency
dropdowns and manual 'Run now' buttons, matching the page's existing
Tailwind conventions.

Tests: SchedulerTest (registry/frequency behavior), ScheduleSettingsTest
(settings UI + authorization), EtsySyncScheduledJobsTest (new commands,
Http::fake only, no live Etsy calls).
This commit is contained in:
2026-11-07 17:38:11 +00:00
parent 9b13640571
commit 960189d14b
12 changed files with 681 additions and 5 deletions
+37
View File
@@ -0,0 +1,37 @@
<?php
namespace App\Console\Commands;
use App\Models\EtsyConnection;
use App\Services\Etsy;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
use Throwable;
#[Signature('etsy:refresh-token')]
#[Description('Proactively refresh the Etsy OAuth access token so the connection survives quiet periods')]
class EtsyRefreshToken extends Command
{
public function handle(Etsy $etsy): int
{
$connection = EtsyConnection::first();
if (! $connection || ! $etsy->configured()) {
$this->line('Etsy token refresh skipped: shop is not configured or not connected.');
return self::SUCCESS;
}
try {
$etsy->refreshAccessToken($connection);
$this->line('etsy token: refreshed, expires at '.$connection->refresh()->expires_at->toIso8601String());
} catch (Throwable $exception) {
$this->warn('etsy token: '.$exception->getMessage());
return self::FAILURE;
}
return self::SUCCESS;
}
}
+42
View File
@@ -0,0 +1,42 @@
<?php
namespace App\Console\Commands;
use App\Models\EtsyConnection;
use App\Services\Etsy;
use Illuminate\Console\Attributes\Description;
use Illuminate\Console\Attributes\Signature;
use Illuminate\Console\Command;
use Throwable;
#[Signature('etsy:sync')]
#[Description('Force a fresh pull of Etsy receipts and active listings into the dashboard cache')]
class EtsySync extends Command
{
public function handle(Etsy $etsy): int
{
$connection = EtsyConnection::first();
if (! $connection || ! $etsy->configured()) {
$this->line('Etsy sync skipped: shop is not configured or not connected.');
return self::SUCCESS;
}
try {
$receipts = $etsy->receipts($connection, fresh: true);
$this->line('etsy receipts: refreshed ('.($receipts['count'] ?? 0).' open)');
} catch (Throwable $exception) {
$this->warn('etsy receipts: '.$exception->getMessage());
}
try {
$listings = $etsy->listings($connection, fresh: true);
$this->line('etsy listings: refreshed ('.count($listings['results'] ?? []).' active)');
} catch (Throwable $exception) {
$this->warn('etsy listings: '.$exception->getMessage());
}
return self::SUCCESS;
}
}
@@ -8,6 +8,7 @@ use App\Models\IntegrationSetting;
use App\Services\Etsy;
use App\Services\IntegrationSettings;
use App\Services\Parcel2Go;
use App\Support\DashboardSchedule;
use Illuminate\Http\RedirectResponse;
use Illuminate\Http\Request;
use Illuminate\View\View;
@@ -24,8 +25,13 @@ class EtsySettingsController extends Controller
$parcel2go = $settings->for('parcel2go');
$bambuddy = $settings->for('bambuddy');
$dryer = $settings->for('dryer');
$scheduleJobs = collect(DashboardSchedule::jobs())
->map(fn (array $job, string $key): array => [...$job, 'key' => $key, 'frequency' => DashboardSchedule::frequencyFor($key)])
->values()->all();
return view('settings.index', [
'scheduleJobs' => $scheduleJobs,
'scheduleFrequencyOptions' => DashboardSchedule::frequencyOptions(),
'storedCredentials' => $credentials !== null,
'configured' => $etsy->configured(),
'shopConnected' => EtsyConnection::query()->exists(),
@@ -0,0 +1,76 @@
<?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'],
'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 : ''));
}
}
+13 -2
View File
@@ -98,14 +98,14 @@ class Etsy
return $total > 0 && $refunded >= $total;
}
public function listings(EtsyConnection $connection): array
public function listings(EtsyConnection $connection, bool $fresh = false): array
{
return $this->cache->remember('etsy.listings.'.$connection->shop_id, 600, fn (): array => $this->request(
'GET',
'application/shops/'.$connection->shop_id.'/listings',
$this->accessToken($connection),
['state' => 'active', 'limit' => 20],
));
), $fresh);
}
/**
@@ -392,6 +392,17 @@ class Etsy
return $this->credentials()['redirect_uri'] ?: route('etsy.callback');
}
/**
* Public wrapper around the on-demand token refresh logic, for the
* etsy:refresh-token scheduled command to call proactively so the OAuth
* connection stays alive even during quiet periods with no receipts or
* listings activity to trigger a refresh as a side effect.
*/
public function refreshAccessToken(EtsyConnection $connection): string
{
return $this->accessToken($connection);
}
private function accessToken(EtsyConnection $connection): string
{
if ($connection->expires_at->isFuture()) {
+175
View File
@@ -0,0 +1,175 @@
<?php
namespace App\Support;
use Illuminate\Console\Scheduling\Event;
use Illuminate\Support\Facades\File;
use Illuminate\Support\Facades\Schedule;
use Throwable;
/**
* Settings-driven Artisan scheduler registry, modelled on LHITS_Dashboard's
* App\Support\DashboardSchedule. HickLab3D has no generic app_settings table
* (unlike LHITS's AppSetting), so the configured frequency is persisted to a
* single JSON file under storage/app and read back here — the same runtime
* mechanism LHITS falls back to when its DB-backed settings aren't available.
*/
class DashboardSchedule
{
/**
* @return array<string, array<string, mixed>>
*/
public static function jobs(): array
{
return [
'integrations_refresh' => [
'name' => 'Integration cache refresh',
'feature' => 'Integrations',
'command' => 'integrations:refresh',
'description' => 'Refreshes cached Etsy, Parcel2Go, BamBuddy and dryer data so dashboard pages load instantly. Migrated from the previous hard-coded schedule entry — frequency and withoutOverlapping(5) behavior unchanged.',
'default_frequency' => 'every_30_seconds',
'overlap_minutes' => 5,
'manual' => true,
],
'alerts_scan' => [
'name' => 'Alert scanner',
'feature' => 'Notifications',
'command' => 'alerts:scan',
'description' => 'Publishes notifications for new orders, print progress, low filament and due shipments. Migrated from the previous hard-coded schedule entry — frequency and withoutOverlapping(5) behavior unchanged.',
'default_frequency' => 'every_30_seconds',
'overlap_minutes' => 5,
'manual' => true,
],
'etsy_sync' => [
'name' => 'Etsy shop sync',
'feature' => 'Etsy',
'command' => 'etsy:sync',
'description' => 'Forces a fresh pull of Etsy receipts and active listings into the same IntegrationCache entries the Etsy page reads, independent of the bundled integrations:refresh job so it can be tuned or disabled on its own.',
'default_frequency' => 'every_15_minutes',
'overlap_minutes' => null,
'manual' => true,
],
'etsy_token_refresh' => [
'name' => 'Etsy token refresh',
'feature' => 'Etsy',
'command' => 'etsy:refresh-token',
'description' => 'Proactively refreshes the Etsy OAuth access token (tokens last ~1 hour) so the connection stays alive even during quiet periods with no receipts or listings activity to trigger an on-demand refresh.',
'default_frequency' => 'every_45_minutes',
'overlap_minutes' => null,
'manual' => true,
],
];
}
/**
* @return array<string, string>
*/
public static function frequencyOptions(): array
{
return [
'disabled' => 'Disabled',
'every_30_seconds' => 'Every 30 seconds',
'every_5_minutes' => 'Every 5 minutes',
'every_10_minutes' => 'Every 10 minutes',
'every_15_minutes' => 'Every 15 minutes',
'every_30_minutes' => 'Every 30 minutes',
'every_45_minutes' => 'Every 45 minutes',
'hourly' => 'Hourly',
'daily_02' => 'Daily at 02:00',
'daily_08' => 'Daily at 08:00',
];
}
public static function frequencyFor(string $jobKey): string
{
$job = self::jobs()[$jobKey] ?? null;
$default = $job['default_frequency'] ?? 'disabled';
return self::runtimeFrequencyFor($jobKey, $default);
}
public static function settingKey(string $jobKey): string
{
return 'schedule.'.$jobKey.'.frequency';
}
/**
* @param array<string, string> $frequencies
*/
public static function persistRuntimeFrequencies(array $frequencies): void
{
$payload = collect($frequencies)
->only(array_keys(self::jobs()))
->filter(fn (string $frequency): bool => array_key_exists($frequency, self::frequencyOptions()))
->all();
File::ensureDirectoryExists(dirname(self::runtimeSettingsPath()));
File::put(self::runtimeSettingsPath(), json_encode($payload, JSON_PRETTY_PRINT | JSON_THROW_ON_ERROR));
}
public static function register(): void
{
foreach (self::jobs() as $jobKey => $job) {
$frequency = self::frequencyFor($jobKey);
if ($frequency === 'disabled' || ! is_string($job['command'] ?? null)) {
continue;
}
$event = self::applyFrequency(Schedule::command($job['command']), $frequency);
$overlap = $job['overlap_minutes'] ?? null;
if ($overlap !== null) {
$event->withoutOverlapping($overlap);
} else {
$event->withoutOverlapping();
}
}
}
private static function runtimeFrequencyFor(string $jobKey, string $default): string
{
if (app()->environment('testing') && ! File::exists(self::runtimeSettingsPath())) {
return $default;
}
try {
if (! File::exists(self::runtimeSettingsPath())) {
return $default;
}
$settings = json_decode((string) File::get(self::runtimeSettingsPath()), true, 512, JSON_THROW_ON_ERROR);
} catch (Throwable) {
return $default;
}
$stored = is_array($settings) ? ($settings[$jobKey] ?? $default) : $default;
return is_string($stored) && array_key_exists($stored, self::frequencyOptions()) ? $stored : $default;
}
public static function runtimeSettingsPath(): string
{
if (app()->environment('testing')) {
return storage_path('framework/testing/dashboard-schedules.json');
}
return storage_path('app/dashboard-schedules.json');
}
private static function applyFrequency(Event $event, string $frequency): Event
{
return match ($frequency) {
'every_30_seconds' => $event->everyThirtySeconds(),
'every_5_minutes' => $event->everyFiveMinutes(),
'every_10_minutes' => $event->everyTenMinutes(),
'every_15_minutes' => $event->everyFifteenMinutes(),
'every_30_minutes' => $event->everyThirtyMinutes(),
'every_45_minutes' => $event->cron('*/45 * * * *'),
'hourly' => $event->hourly(),
'daily_02' => $event->dailyAt('02:00'),
'daily_08' => $event->dailyAt('08:00'),
default => $event->hourly(),
};
}
}