Files
fewo-stommer/app/Actions/MonitorChannels.php
2026-10-23 07:14:25 +02:00

65 lines
1.8 KiB
PHP

<?php
namespace App\Actions;
use App\Channels\Mail\MailboxReader;
use App\Mail\ChannelSyncAlert;
use App\Mail\MailboxAlert;
use App\Models\Channel;
use App\Support\Settings;
use Carbon\CarbonImmutable;
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Mail;
/**
* Alerts the landlord once per incident when a portal import or the mailbox fast path fails
* or has not succeeded for too long. The alert is reset by the next success.
*/
class MonitorChannels
{
private const MAILBOX_ALERTED_KEY = 'mailbox:alerted';
public function handle(): int
{
$channels = Channel::query()->active()->whereNull('alerted_at')->get()
->filter(fn (Channel $channel): bool => $channel->isStale());
foreach ($channels as $channel) {
Mail::to(Settings::notificationRecipients())->send(new ChannelSyncAlert($channel));
$channel->forceFill(['alerted_at' => now()])->save();
}
return $channels->count() + $this->monitorMailbox();
}
public static function mailboxIsStale(): bool
{
if (! MailboxReader::isConfigured()) {
return false;
}
$lastSuccess = Cache::get(MailboxReader::LAST_SUCCESS_KEY);
return $lastSuccess === null
|| CarbonImmutable::parse($lastSuccess)->lessThan(now()->subMinutes(config('fewo.mailbox.stale_after_minutes')));
}
private function monitorMailbox(): int
{
if (! self::mailboxIsStale()) {
Cache::forget(self::MAILBOX_ALERTED_KEY);
return 0;
}
if (Cache::has(self::MAILBOX_ALERTED_KEY)) {
return 0;
}
Mail::to(Settings::notificationRecipients())->send(new MailboxAlert(Cache::get(MailboxReader::LAST_ERROR_KEY)));
Cache::forever(self::MAILBOX_ALERTED_KEY, true);
return 1;
}
}