Files
dpl/app/Console/Commands/ReportMailUsage.php
T

42 lines
2.0 KiB
PHP

<?php
namespace App\Console\Commands;
use App\Models\MailDailyReport;
use App\Services\MailFlow\DailyReportService;
use App\Services\MailFlow\Settings;
use Illuminate\Console\Command;
class ReportMailUsage extends Command
{
protected $signature = 'mail:report-usage';
protected $description = 'Report the latest complete 08:00-to-08:00 mail period through TeleHub';
public function handle(DailyReportService $reports): int
{
if (!Settings::get('enabled') || !Settings::get('report_enabled')
|| !config('mail_report.enabled', false) || config('app.env') !== 'production') return self::SUCCESS;
try {
$startDate = (string) config('mail_report.start_date');
if (!preg_match('/\A\d{4}-\d{2}-\d{2}\z/D', $startDate)) throw new \RuntimeException('mail_report_start_required');
$now = now()->setTimezone('Asia/Shanghai');
$end = $now->copy()->startOfDay()->setTime(8, 0);
if ($now->lt($end)) $end->subDay();
if ($end->copy()->subDay()->toDateString() >= $startDate) $reports->snapshot($end->utc());
$attention = false;
MailDailyReport::where('report_date', '>=', $startDate)->whereIn('status', ['pending', 'queued', 'sending'])
->orderBy('id')->limit(10)->get()->each(function ($report) use ($reports, &$attention) {
$reports->send($report);
$report->refresh();
$attention = $attention || in_array($report->status, ['failed', 'unknown', 'uncertain'], true) || $report->error_code !== null;
$this->line(json_encode(['id' => $report->id, 'report_date' => $report->report_date, 'status' => $report->status,
'error_code' => $report->error_code], JSON_UNESCAPED_UNICODE|JSON_THROW_ON_ERROR));
});
return $attention ? self::FAILURE : self::SUCCESS;
} catch (\Throwable $e) {
$this->error('mail_report_failed_closed: ' . get_class($e));
return self::FAILURE;
}
}
}