Compare commits
1
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
edb0cc30b2 |
No files matched your search
@@ -10,17 +10,32 @@ use Illuminate\Console\Command;
|
||||
class ReportMailUsage extends Command
|
||||
{
|
||||
protected $signature = 'mail:report-usage';
|
||||
protected $description = 'Snapshot the complete 08:00-to-08:00 mail period and report to master';
|
||||
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')) { return self::SUCCESS; }
|
||||
// 00:00 UTC is 08:00 Asia/Shanghai, independent of the application's timezone.
|
||||
$reports->snapshot(now()->utc()->startOfDay());
|
||||
MailDailyReport::where(function ($query) {
|
||||
$query->whereIn('status', ['pending', 'failed'])->orWhere(fn ($q) => $q->where('status', 'sending')->where('updated_at', '<', now()->subMinutes(2)));
|
||||
})->where('attempts', '<', 3)
|
||||
->orderBy('id')->limit(10)->get()->each(fn ($report) => $reports->send($report));
|
||||
return self::SUCCESS;
|
||||
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;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -40,60 +40,135 @@ class DailyReportService
|
||||
return MailDailyReport::firstOrCreate(['report_date' => $start->toDateString()], ['summary' => $summary]);
|
||||
}
|
||||
|
||||
private const TERMINAL = ['sent', 'failed', 'uncertain', 'cancelled'];
|
||||
|
||||
public function send(MailDailyReport $report): void
|
||||
{
|
||||
if (!config('mail_report.enabled', false) || config('app.env') !== 'production'
|
||||
|| !Settings::get('enabled') || !Settings::get('report_enabled')) return;
|
||||
$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');
|
||||
if (substr((string) $report->report_date, 0, 10) < $startDate) return;
|
||||
$lock = Cache::lock('mailflow:report:' . $report->id, 60);
|
||||
if (!$lock->get()) { return; }
|
||||
if (!$lock->get()) return;
|
||||
try {
|
||||
$report->refresh();
|
||||
if ($report->status === 'sending') {
|
||||
$report->update(['status' => 'unknown', 'error_code' => 'master_worker_interrupted']);
|
||||
}
|
||||
if (!in_array($report->status, ['pending', 'failed'], true)) { return; }
|
||||
$url = (string) Settings::get('master_url');
|
||||
if (!str_starts_with($url, 'https://') || !filter_var($url, FILTER_VALIDATE_URL)
|
||||
|| !Settings::get('master_bot_code') || !Settings::get('master_chat_code')) {
|
||||
$report->update(['error_code' => 'master_configuration_required']);
|
||||
return;
|
||||
}
|
||||
$report->increment('attempts');
|
||||
$report->update(['status' => 'sending']);
|
||||
$summary = $report->summary;
|
||||
$text = '📧 ' . admin_setting('app_name', 'dpl') . ' 邮件日报(北京时间八点结算)';
|
||||
foreach ($summary['counts'] as $key => $count) {
|
||||
[$direction, $channel, $status] = explode('/', $key);
|
||||
$labels = ['out' => '发送', 'in' => '收件', 'policy' => '邮件策略', 'resend' => 'Resend', 'conventional' => '常规邮箱', 'pending' => '待处理', 'submitted' => '已提交', 'delivered' => '已投递', 'delayed' => '投递延迟', 'bounced' => '退信', 'complained' => '投诉', 'suppressed' => '停止投递', 'failed' => '失败', 'unknown' => '结果未知', 'sending' => '提交中', 'received' => '已接收', 'simulated' => '模拟发送', 'expired' => '已过期', 'policy_blocked' => '因档位或套餐状态取消'];
|
||||
$text .= "\n" . ($labels[$direction] ?? $direction) . ' / ' . ($labels[$channel] ?? $channel) . ' / ' . ($labels[$status] ?? $status) . ':' . $count;
|
||||
$event = $summary['_telehub'] ?? null;
|
||||
if ($event === null) {
|
||||
// A legacy submission, failed attempt or unknown result must never become a new TeleHub delivery.
|
||||
if ($report->status !== 'pending' || (int) $report->attempts !== 0) return;
|
||||
$event = ['version' => 1, 'identity' => $this->identity(),
|
||||
'key' => 'xb.mail.daily.' . $this->identity() . '.' . substr((string) $report->report_date, 0, 10),
|
||||
'bot' => 'info', 'target' => 'base', 'text' => $this->text($report), 'retry_at' => 0];
|
||||
$summary['_telehub'] = $event;
|
||||
$report->update(['summary' => $summary]); // Freeze identity/key/body before the first HTTP attempt.
|
||||
}
|
||||
$text .= "\n回退常规邮箱:" . $summary['fallbacks'] . "\n待处理/结果未知:" . $summary['backlog'];
|
||||
if ($summary['resend_usage'] ?? null) {
|
||||
$monthly = $summary['resend_usage']['monthly'] ?? [];
|
||||
if (isset($monthly['used'], $monthly['limit'])) {
|
||||
$text .= "\nResend 官方本月已用:" . $monthly['used'] . ' / ' . $monthly['limit'];
|
||||
}
|
||||
} else {
|
||||
$text .= "\nResend 官方额度未能实时核对,以下为本地记录。";
|
||||
if (!is_array($event) || ($event['version'] ?? null) !== 1 || ($event['identity'] ?? null) !== $this->identity()
|
||||
|| ($event['bot'] ?? null) !== 'info' || ($event['target'] ?? null) !== 'base'
|
||||
|| !is_string($event['key'] ?? null) || !preg_match('/\A[A-Za-z0-9._:-]{1,128}\z/D', $event['key'])
|
||||
|| !is_string($event['text'] ?? null) || (isset($event['receipt_id']) && !$this->uuid($event['receipt_id']))) {
|
||||
throw new \RuntimeException('mail_report_state_invalid');
|
||||
}
|
||||
foreach ($summary['quota'] as $quota) {
|
||||
$text .= "\nResend " . $quota['period'] . ' 保守剩余额度:' . max(0, $quota['limit'] - $quota['used'] - $quota['reserved']);
|
||||
}
|
||||
try {
|
||||
// Master currently exposes no idempotency guarantee. An uncertain response is not auto-retried.
|
||||
$response = Http::connectTimeout(3)->timeout(8)->post(rtrim($url, '/') . '/api/telegram/post', [
|
||||
'sBotCode' => Settings::get('master_bot_code'), 'sChatCode' => Settings::get('master_chat_code'),
|
||||
'sMsg' => $text, 'enableMasterQueue' => false,
|
||||
]);
|
||||
} catch (\Throwable $e) {
|
||||
$report->update(['status' => 'unknown', 'error_code' => 'master_transport_unknown']);
|
||||
if (in_array($report->status, self::TERMINAL, true) || ($event['blocked'] ?? false)) return;
|
||||
if (now()->timestamp < ($event['retry_at'] ?? 0)) return;
|
||||
$base = rtrim((string) config('mail_report.telehub_url'), '/');
|
||||
$key = (string) config('mail_report.telehub_key');
|
||||
if (!$key || parse_url($base, PHP_URL_SCHEME) !== 'https' || !parse_url($base, PHP_URL_HOST)
|
||||
|| parse_url($base, PHP_URL_USER) || parse_url($base, PHP_URL_PASS)) {
|
||||
$report->update(['error_code' => 'telehub_configuration_required']);
|
||||
return;
|
||||
}
|
||||
if ($response->successful() && $response->json('isDone') === true) {
|
||||
$report->update(['status' => 'submitted', 'submitted_at' => now(), 'error_code' => null]);
|
||||
} else {
|
||||
$report->update(['status' => 'unknown', 'error_code' => 'master_response_unknown']);
|
||||
$event['retry_at'] = now()->timestamp + max(60, (int) config('mail_report.retry_seconds', 300));
|
||||
$summary['_telehub'] = $event;
|
||||
$report->update(['summary' => $summary, 'attempts' => (int) $report->attempts + 1]);
|
||||
try {
|
||||
$client = Http::withoutRedirecting()->connectTimeout(5)->timeout(15)->withToken($key);
|
||||
$response = isset($event['receipt_id'])
|
||||
? $client->get($base . '/api/v1/messages/' . $event['receipt_id'])
|
||||
: $client->withHeaders(['Idempotency-Key' => $event['key']])->post($base . '/api/v1/messages', [
|
||||
'bot' => 'info', 'target' => 'base', 'text' => $event['text'],
|
||||
]);
|
||||
} catch (\Throwable $e) {
|
||||
$report->update(['error_code' => 'telehub_transport_unknown']);
|
||||
return; // Same immutable key/body is safe to retry; never fall back to master or direct Telegram.
|
||||
}
|
||||
if (!in_array($response->status(), [200, 202], true)) {
|
||||
$updates = ['error_code' => 'telehub_http_' . $response->status()];
|
||||
if ($response->status() === 429) {
|
||||
$event['retry_at'] = now()->timestamp + max(60, min(86400, (int) $response->header('Retry-After', 300)));
|
||||
} elseif (in_array($response->status(), [400, 401, 403, 404, 409, 422], true)) {
|
||||
$event['blocked'] = true;
|
||||
$updates['status'] = 'failed';
|
||||
}
|
||||
$summary['_telehub'] = $event;
|
||||
$report->update($updates + ['summary' => $summary]);
|
||||
return;
|
||||
}
|
||||
$data = $response->json('data');
|
||||
$id = is_array($data) ? ($data['id'] ?? null) : null;
|
||||
$status = is_array($data) ? ($data['status'] ?? null) : null;
|
||||
if (!$this->uuid($id) || !in_array($status, ['queued', 'sending', ...self::TERMINAL], true)
|
||||
|| isset($event['receipt_id']) && $event['receipt_id'] !== $id) {
|
||||
$report->update(['error_code' => 'telehub_response_invalid']);
|
||||
return;
|
||||
}
|
||||
$event['receipt_id'] = $id;
|
||||
$summary['_telehub'] = $event;
|
||||
$updates = ['summary' => $summary, 'status' => $status,
|
||||
'error_code' => in_array($status, ['failed', 'uncertain'], true) ? 'telehub_delivery_' . $status : null];
|
||||
if (!$report->submitted_at) $updates['submitted_at'] = now();
|
||||
$report->update($updates);
|
||||
} finally {
|
||||
$lock->release();
|
||||
}
|
||||
}
|
||||
|
||||
private function identity(): string
|
||||
{
|
||||
$driver = (string) config('database.default');
|
||||
return substr(hash('sha256', implode('|', [(string) config('app.env'), (string) config('mail_report.project'),
|
||||
(string) config('app.url'), $driver, (string) config('database.connections.' . $driver . '.database')])), 0, 24);
|
||||
}
|
||||
|
||||
private function uuid(mixed $id): bool
|
||||
{
|
||||
return is_string($id) && preg_match('/\A[0-9a-f]{8}(?:-[0-9a-f]{4}){3}-[0-9a-f]{12}\z/iD', $id) === 1;
|
||||
}
|
||||
|
||||
private function text(MailDailyReport $report): string
|
||||
{
|
||||
$project = trim(preg_replace('/[\x00-\x1f\x7f]+/u', ' ', (string) config('mail_report.project')));
|
||||
if ($project === '' || mb_strlen($project) > 100) throw new \RuntimeException('mail_report_project_invalid');
|
||||
$summary = $report->summary;
|
||||
$from = Carbon::parse($summary['from'])->setTimezone('Asia/Shanghai')->format('Y-m-d H:i');
|
||||
$to = Carbon::parse($summary['to'])->setTimezone('Asia/Shanghai')->format('Y-m-d H:i');
|
||||
$text = '【' . $project . '/' . config('app.env') . ' - 邮件与Resend用量日报】';
|
||||
$text .= "\n统计区间:" . $from . '–' . $to . '(北京时间)';
|
||||
$labels = ['out' => '发送', 'in' => '收件', 'policy' => '邮件策略', 'resend' => 'Resend', 'conventional' => '常规邮箱',
|
||||
'pending' => '待处理', 'submitted' => '已提交', 'delivered' => '已投递', 'delayed' => '投递延迟', 'bounced' => '退信',
|
||||
'complained' => '投诉', 'suppressed' => '停止投递', 'failed' => '失败', 'unknown' => '结果未知', 'sending' => '提交中',
|
||||
'received' => '已接收', 'simulated' => '模拟发送', 'expired' => '已过期', 'policy_blocked' => '因档位或套餐状态取消'];
|
||||
foreach ($summary['counts'] as $key => $count) {
|
||||
[$direction, $channel, $status] = explode('/', $key);
|
||||
$text .= "\n" . ($labels[$direction] ?? $direction) . ' / ' . ($labels[$channel] ?? $channel)
|
||||
. ' / ' . ($labels[$status] ?? $status) . ':' . $count;
|
||||
}
|
||||
if (!$summary['counts']) $text .= "\n期间邮件记录:0";
|
||||
$text .= "\n回退常规邮箱:" . $summary['fallbacks'] . "\n待处理/结果未知:" . $summary['backlog'];
|
||||
if ($summary['resend_usage'] ?? null) {
|
||||
foreach (['daily' => '今日', 'monthly' => '本月'] as $period => $label) {
|
||||
$usage = $summary['resend_usage'][$period] ?? [];
|
||||
if (isset($usage['used'], $usage['limit'])) $text .= "\nResend 官方" . $label . '已用:' . $usage['used'] . ' / ' . $usage['limit'];
|
||||
}
|
||||
} else {
|
||||
$text .= "\nResend 官方额度未能实时核对,以下为本地记录。";
|
||||
}
|
||||
foreach ($summary['quota'] as $quota) {
|
||||
$period = ['daily' => '日', 'monthly' => '月'][$quota['period']] ?? $quota['period'];
|
||||
$text .= "\nResend " . $period . '保守剩余额度:' . max(0, $quota['limit'] - $quota['used'] - $quota['reserved']);
|
||||
}
|
||||
if (mb_strlen($text) > 4096) throw new \RuntimeException('mail_report_text_too_long');
|
||||
return $text;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
<?php
|
||||
// Private reporting configuration is separate from publicly returned MailFlow settings.
|
||||
return [
|
||||
'enabled' => env('MAIL_REPORT_TELEHUB_ENABLED', false),
|
||||
'project' => env('MAIL_REPORT_PROJECT', env('XB_INSTANCE', env('SITE_PROFILE', env('APP_NAME', 'xb')))),
|
||||
'telehub_url' => env('MAIL_REPORT_TELEHUB_URL', 'https://telehub.gemcook.net'),
|
||||
'telehub_key' => env('MAIL_REPORT_TELEHUB_KEY', ''),
|
||||
// Start date of the first eligible 08:00-to-08:00 period, not its ending date.
|
||||
'start_date' => env('MAIL_REPORT_START_DATE'),
|
||||
'retry_seconds' => 300,
|
||||
];
|
||||
@@ -0,0 +1,44 @@
|
||||
# 邮件与 Resend 用量日报接入 TeleHub
|
||||
|
||||
## 批准与范围
|
||||
|
||||
2026-10-31用户明确批准核心方案并同时上线DPL/HN:共用MailFlow/DailyReportService、mail:report-usage及专用配置/测试,将原master邮件日报迁到TeleHub info/base,保持原收发统计、Resend用量与额度、北京时间08:00–08:00统计和历史记录;新增稳定幂等键/回执,不重发旧已提交或未知日报。此次不改邮件发送、IMAP、自动回复、Resend投递回调/密钥或原业务用户/订单。
|
||||
|
||||
迁移前服务器只读核实:DPL日报开启、旧master路由已配置,历史21条submitted、1条unknown;最新report_date=2026-10-30,2026-10-31 08:00已提交。HN邮件/Resend开启,日报关闭、无旧路由或历史日报。旧master的submitted只代表当时接口受理,不能改写成新版TeleHub sent。
|
||||
|
||||
## 统计及调度
|
||||
|
||||
仍使用各实例原v2_mail_daily_reports与邮件/额度表,不新增数据库结构。report_date沿用统计开始日期,不改历史日期语义;正文显示完整开始/结束时间。每天北京时间08:00与每5分钟补偿由site-jp02原cron显式XB_INSTANCE执行。八点前只处理最近一个已结束的08:00周期,不生成尚未结束的区间。午夜UTC就是北京时间08:00,统计实际提交/首次尝试/建立时间的原规则保持。
|
||||
|
||||
正文标题为【DPL/production - 邮件与Resend用量日报】或HN,含收发渠道/投递状态计数、回退常规邮箱次数、待处理/未知数量、Resend官方日/月用量及本地保守剩余额度;官方查询失败明确标记未核对。零量也可汇报。不包含收件人、邮件正文/主题、验证码或秘密。
|
||||
|
||||
## 私密配置与路由
|
||||
|
||||
现有mailflow.enabled和report_enabled继续控制业务日报;新增独立config/mail_report.php,避免API Key被Settings::publicSettings()返回:
|
||||
|
||||
- MAIL_REPORT_TELEHUB_ENABLED:默认false;生产准备完成后开启,local/testing不外发。
|
||||
- MAIL_REPORT_PROJECT:DPL/HN项目代号;MAIL_REPORT_TELEHUB_URL使用已登记TeleHub生产基址。
|
||||
- MAIL_REPORT_TELEHUB_KEY:本实例邮件日报专用调用方,只授权info/base;仅存项目服务器原私密.env,不与支付或注册日报混用。
|
||||
- MAIL_REPORT_START_DATE:首个允许接入的统计开始日期,本批2026-10-30。不是结束日期;它只限制本次新通道,不补历史。
|
||||
|
||||
新接口只POST bot/target/text到/api/v1/messages;Bearer及Idempotency-Key按协议传递。旧master_url/master_bot_code/master_chat_code配置和界面字段保留历史兼容,但不再用于邮件日报;修改旧字段不改变新路由。不会回退旧master、其他机器人或直连Telegram;TeleHub全局投递、机器人、其他调用方权限均不改。
|
||||
|
||||
## 迁移、幂等与回执
|
||||
|
||||
日报summary原统计冻结不变,新增_telehub元数据保存身份摘要、稳定键、同一正文、重试时间及UUID,先持久化后HTTP。身份包含环境、项目、app.url与数据库;错实例/损坏状态失败关闭。键格式xb.mail.daily.<identity>.<开始日期>。没有令牌写进该元数据。
|
||||
|
||||
仅pending且attempts=0的未尝试记录可以首次接入;原submitted/unknown/sending/failed或已尝试pending不转成新发送。旧DPL当天已提交记录保留,因此首个DPL新通道正常日报应为2026-11-01 08:00;HN可汇报本次最近完整周期,无历史批量补发。
|
||||
|
||||
HTTP超时/5xx复用同一键和正文,重试间隔至少5分钟;429遵守有界Retry-After。取得UUID后只GET原回执,queued/sending不能冒充投递成功;sent才表示Telegram确认,failed/uncertain/cancelled停止自动重发。401/403/409/422等明确错误阻断并保留错误类别,不换路由。attempts字段现在统计本地API请求次数(含查询),TeleHub回执attempts才是实际投递次数,不能混为一谈。
|
||||
|
||||
## 验证和发布
|
||||
|
||||
代码与原MailFlow、支付、注册日报、主题/实例隔离一并隔离回归:122项PHP测试、610断言通过。新增14项涵盖完整区间、零量、用量/额度、隐私、先存后发、固定重试、只GET回执、旧日报保护、八点前补偿、迁移日期、关闭/非生产/缺配置、403/429、uncertain、UUID不匹配和实例身份;HTTP全部模拟,不从本机请求生产。
|
||||
|
||||
线上按用户批准Git提交/推送/检出,旧代码/env/mail_flow设置/日报保存在site-jp02 /root/codex-backups/mail-report-telehub-20261031(700,私密文件600)。先准备独立调用方且新开关false,再更新共用代码、配置缓存,最后两站启用;HN首次真实日报与DPL已提交保护分别验收。生产结果尚待本节后续记录。
|
||||
|
||||
## 停用与恢复
|
||||
|
||||
单停某实例邮件日报:MAIL_REPORT_TELEHUB_ENABLED=false,以原用户、正确XB_INSTANCE刷新config:cache;不停止整个scheduler或其他邮件任务。业务report_enabled可继续独立控制。原邮件收发链路和注册/支付汇报不随本项停止。
|
||||
|
||||
回退代码前先将该专用开关关闭,同时将该实例mail_flow.report_enabled关闭并核对缓存,避免旧代码重新走master;然后按明确Git提交局部恢复代码,保留新旧日报summary、UUID、状态和调用方记录。不得把sent改回pending、删除记录重发或整库回滚。恢复旧master路由须另行明确决定,不能把Git回退当作自动授权旧通道重新外发;若.env或mail_flow有并行更新,按字段合并,不能整文件/设置覆盖。
|
||||
@@ -23,6 +23,7 @@
|
||||
|
||||
| 文件 | 用途 |
|
||||
| --- | --- |
|
||||
| MAIL_REPORT_TELEHUB.md | DPL/HN邮件与Resend用量日报迁到TeleHub、历史保护、幂等回执及恢复 |
|
||||
| REGISTRATION_REPORT.md | 各实例默认每天08:00汇报昨日08点至今日08点注册量,TeleHub info/base、幂等回执及回退 |
|
||||
| PAYMENT_HEALTH.md | 共用支付每6小时检测、自动开关、人工停用/旧回调保护、独立TeleHub告警与生产验收 |
|
||||
| RESOURCE_CLIENT_DOWNLOADS.md | DPL客户端下载接入resource、固定链接、架构选择、Git迁移版本与验收/回退 |
|
||||
|
||||
@@ -297,26 +297,25 @@ class MailFlowTest extends TestCase
|
||||
public function test_daily_report_snapshots_exact_complete_period_and_submits_only_once(): void
|
||||
{
|
||||
$this->travelTo(\Carbon\Carbon::parse('2026-10-09 08:00:00', 'Asia/Shanghai'));
|
||||
config(['mailflow.master_url' => 'https://master.example.com', 'mailflow.master_bot_code' => 'bot', 'mailflow.master_chat_code' => 'chat']);
|
||||
MailMessage::create(['message_key' => 'previous', 'purpose' => 'verification', 'email' => '[email protected]', 'subject' => 'Test', 'status' => 'delivered', 'channel' => 'resend', 'created_at' => now()->subMinute()]);
|
||||
MailMessage::create(['message_key' => 'next', 'purpose' => 'verification', 'email' => '[email protected]', 'subject' => 'Test', 'created_at' => now()]);
|
||||
$service = app(DailyReportService::class);
|
||||
$report = $service->snapshot(now()->utc()->startOfDay());
|
||||
$this->assertSame(['out/resend/delivered' => 1], $report->summary['counts']);
|
||||
Http::fake(['*/api/telegram/post' => Http::response(['isDone' => true])]);
|
||||
$service->send($report); $service->send($report);
|
||||
$this->assertSame('submitted', $report->refresh()->status);
|
||||
Http::assertSentCount(1);
|
||||
config(['app.env'=>'production','mailflow.resend_enabled'=>false,'mailflow.report_enabled'=>true,'mail_report.enabled'=>true,'mail_report.start_date'=>'2026-10-08','mail_report.project'=>'DPL','mail_report.telehub_url'=>'https://telehub.example.test','mail_report.telehub_key'=>'test-private-key']);
|
||||
MailMessage::create(['message_key'=>'previous','purpose'=>'verification','email'=>'[email protected]','subject'=>'Test','status'=>'delivered','channel'=>'resend','created_at'=>now()->subMinute()]);
|
||||
MailMessage::create(['message_key'=>'next','purpose'=>'verification','email'=>'[email protected]','subject'=>'Test','created_at'=>now()]);
|
||||
$service=app(DailyReportService::class);$report=$service->snapshot(now()->utc()->startOfDay());
|
||||
$this->assertSame(['out/resend/delivered'=>1],$report->summary['counts']);
|
||||
Http::fake(['*/api/v1/messages'=>Http::response(['data'=>['id'=>'12345678-1234-1234-1234-123456789abc','status'=>'queued']],202)]);
|
||||
$service->send($report);$service->send($report);
|
||||
$this->assertSame('queued',$report->refresh()->status);Http::assertSentCount(1);
|
||||
Http::assertSent(fn($r)=>$r['bot']==='info'&&$r['target']==='base'&&str_contains($r['text'],'【DPL/production - 邮件与Resend用量日报】'));
|
||||
}
|
||||
|
||||
public function test_master_timeout_is_unknown_and_not_automatically_repeated(): void
|
||||
public function test_telehub_timeout_retries_same_frozen_key_instead_of_sending_a_new_message(): void
|
||||
{
|
||||
config(['mailflow.master_url' => 'https://master.example.com', 'mailflow.master_bot_code' => 'bot', 'mailflow.master_chat_code' => 'chat']);
|
||||
Http::fake(['*/api/telegram/post' => Http::failedConnection()]);
|
||||
$service = app(DailyReportService::class); $report = $service->snapshot(now()->utc()->startOfDay());
|
||||
$service->send($report); $service->send($report);
|
||||
$this->assertSame('unknown', $report->refresh()->status);
|
||||
$this->assertSame(1, $report->attempts);
|
||||
$this->travelTo(\Carbon\Carbon::parse('2026-10-09 08:00:00','Asia/Shanghai'));
|
||||
config(['app.env'=>'production','mailflow.resend_enabled'=>false,'mailflow.report_enabled'=>true,'mail_report.enabled'=>true,'mail_report.start_date'=>'2026-10-08','mail_report.project'=>'DPL','mail_report.telehub_url'=>'https://telehub.example.test','mail_report.telehub_key'=>'test-private-key']);
|
||||
Http::fake(['*/api/v1/messages'=>Http::failedConnection()]);
|
||||
$service=app(DailyReportService::class);$report=$service->snapshot(now()->utc()->startOfDay());$service->send($report);$service->send($report);
|
||||
$this->assertSame('pending',$report->refresh()->status);$this->assertSame('telehub_transport_unknown',$report->error_code);$this->assertSame(1,$report->attempts);
|
||||
$frozen=$report->summary['_telehub'];$this->travel(6)->minutes();$service->send($report);$this->assertSame($frozen['key'],$report->refresh()->summary['_telehub']['key']);$this->assertSame($frozen['text'],$report->summary['_telehub']['text']);$this->assertSame(2,$report->attempts);
|
||||
}
|
||||
|
||||
public function test_payload_is_encrypted_and_public_settings_hide_secrets(): void
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
<?php
|
||||
namespace Tests\Feature\MailFlow;
|
||||
|
||||
use App\Models\{MailDailyReport,MailMessage,MailQuotaBucket};
|
||||
use App\Services\MailFlow\{DailyReportService,Settings};
|
||||
use Carbon\Carbon;
|
||||
use Illuminate\Database\Schema\Blueprint;
|
||||
use Illuminate\Support\Facades\{Cache,DB,Http,Schema};
|
||||
use Tests\TestCase;
|
||||
|
||||
class TeleHubMailReportTest extends TestCase
|
||||
{
|
||||
private const UUID='12345678-1234-1234-1234-123456789abc';
|
||||
protected function setUp():void
|
||||
{
|
||||
parent::setUp();
|
||||
config(['database.default'=>'sqlite','database.connections.sqlite.database'=>':memory:','cache.default'=>'array','cache.stores.redis'=>['driver'=>'array'],'app.key'=>'base64:'.base64_encode(str_repeat('a',32)),'queue.default'=>'sync','app.env'=>'production']);
|
||||
DB::purge('sqlite');Cache::forgetDriver(['redis','array']);$this->app->forgetInstance(\App\Support\Setting::class);
|
||||
Schema::create('v2_settings',fn(Blueprint $t)=>[$t->id(),$t->string('name'),$t->text('value')->nullable(),$t->timestamps()]);
|
||||
(require base_path('database/migrations/2026_10_09_170000_create_mail_flow_tables.php'))->up();Cache::flush();
|
||||
config(['mailflow.enabled'=>true,'mailflow.resend_enabled'=>false,'mailflow.report_enabled'=>true,'mail_report.enabled'=>true,'mail_report.project'=>'DPL','mail_report.telehub_url'=>'https://telehub.example.test','mail_report.telehub_key'=>'private-report-key','mail_report.start_date'=>'2026-10-30','mail_report.retry_seconds'=>300]);
|
||||
$this->travelTo(Carbon::parse('2026-10-31 08:00:00','Asia/Shanghai'));Http::preventStrayRequests();
|
||||
}
|
||||
private function report():MailDailyReport {return app(DailyReportService::class)->snapshot(now()->utc()->startOfDay());}
|
||||
private function fake(string $status='queued',int $code=202):void {Http::fake(['*/api/v1/messages'=>Http::response(['data'=>['id'=>self::UUID,'status'=>$status]],$code)]);}
|
||||
private function message(string $key,string $time):void {MailMessage::create(['message_key'=>$key,'email'=>'[email protected]','subject'=>'private-subject','purpose'=>'verification','channel'=>'resend','status'=>'delivered','created_at'=>Carbon::parse($time,'Asia/Shanghai')]);}
|
||||
|
||||
public function test_counts_usage_and_quota_are_reported_without_email_or_secrets():void
|
||||
{
|
||||
$this->message('mail','2026-10-30 10:00');$r=$this->report();$s=$r->summary;$s['resend_usage']=['daily'=>['used'=>3,'limit'=>100],'monthly'=>['used'=>9,'limit'=>3000]];$s['quota']=[['period'=>'daily','limit'=>100,'used'=>3,'reserved'=>2]];$r->update(['summary'=>$s]);$this->fake();app(DailyReportService::class)->send($r);
|
||||
$text=$r->refresh()->summary['_telehub']['text'];$this->assertStringContainsString('2026-10-30 08:00–2026-10-31 08:00',$text);$this->assertStringContainsString('发送 / Resend / 已投递:1',$text);$this->assertStringContainsString('官方本月已用:9 / 3000',$text);$this->assertStringContainsString('日保守剩余额度:95',$text);$this->assertStringNotContainsString('private-user',$text);$this->assertStringNotContainsString('private-subject',$text);$this->assertStringNotContainsString('private-report-key',$text);
|
||||
}
|
||||
public function test_queued_receipt_is_polled_and_sent_is_terminal():void
|
||||
{
|
||||
$this->fake();$s=app(DailyReportService::class);$r=$this->report();$s->send($r);$this->assertSame('queued',$r->refresh()->status);$this->travel(6)->minutes();Http::fake(['*/api/v1/messages/'.self::UUID=>Http::response(['data'=>['id'=>self::UUID,'status'=>'sent']],200)]);$s->send($r);$s->send($r);$this->assertSame('sent',$r->refresh()->status);Http::assertSent(fn($q)=>$q->method()==='GET');Http::assertNotSent(fn($q)=>$q->method()==='POST');
|
||||
}
|
||||
public function test_lost_post_response_reuses_body_and_key_even_after_summary_changes():void
|
||||
{
|
||||
$fail=true;Http::fake(['*/api/v1/messages'=>function()use(&$fail){if($fail)throw new \Illuminate\Http\Client\ConnectionException('simulated');return Http::response(['data'=>['id'=>self::UUID,'status'=>'queued']],202);}]);$s=app(DailyReportService::class);$r=$this->report();$s->send($r);$event=$r->refresh()->summary['_telehub'];$summary=$r->summary;$summary['counts']=['out/resend/delivered'=>999];$r->update(['summary'=>$summary]);$this->travel(6)->minutes();$fail=false;$s->send($r);Http::assertSent(fn($q)=>$q->hasHeader('Idempotency-Key',$event['key'])&&$q['text']===$event['text']);$this->assertSame('queued',$r->refresh()->status);
|
||||
}
|
||||
public function test_all_legacy_attempted_or_unknown_reports_are_preserved_without_http():void
|
||||
{
|
||||
$r=$this->report();foreach(['submitted','unknown','sending','failed'] as $status){$r->update(['status'=>$status,'attempts'=>1]);app(DailyReportService::class)->send($r);$this->assertSame($status,$r->refresh()->status);$this->assertArrayNotHasKey('_telehub',$r->summary);}$r->update(['status'=>'pending','attempts'=>1]);app(DailyReportService::class)->send($r);$this->assertArrayNotHasKey('_telehub',$r->refresh()->summary);Http::assertNothingSent();
|
||||
}
|
||||
public function test_legacy_submitted_current_day_is_not_replaced_by_command():void
|
||||
{
|
||||
$r=$this->report();$r->update(['status'=>'submitted','attempts'=>1]);$this->artisan('mail:report-usage')->assertExitCode(0);$this->assertSame(1,MailDailyReport::count());$this->assertSame('submitted',$r->refresh()->status);Http::assertNothingSent();
|
||||
}
|
||||
public function test_early_retry_uses_last_completed_eight_to_eight_period():void
|
||||
{
|
||||
$this->travelTo(Carbon::parse('2026-11-02 07:55:00','Asia/Shanghai'));
|
||||
foreach(['before'=>'2026-10-31 07:59:59','start'=>'2026-10-31 08:00:00','inside'=>'2026-11-01 07:59:59','end'=>'2026-11-01 08:00:00'] as $key=>$time)$this->message($key,$time);
|
||||
$this->fake();$this->artisan('mail:report-usage')->assertExitCode(0);$r=MailDailyReport::first();$this->assertSame('2026-10-31',$r->report_date);$this->assertSame(['out/resend/delivered'=>2],$r->summary['counts']);$this->assertStringContainsString('2026-10-31 08:00–2026-11-01 08:00',$r->summary['_telehub']['text']);
|
||||
}
|
||||
public function test_future_start_date_prevents_historical_snapshot_or_send():void
|
||||
{
|
||||
config(['mail_report.start_date'=>'2026-11-01']);$this->artisan('mail:report-usage')->assertExitCode(0);$this->assertSame(0,MailDailyReport::count());Http::assertNothingSent();
|
||||
}
|
||||
public function test_disabled_local_and_missing_key_do_not_call_telehub():void
|
||||
{
|
||||
$r=$this->report();$s=app(DailyReportService::class);config(['mail_report.enabled'=>false]);$s->send($r);config(['mail_report.enabled'=>true,'app.env'=>'local']);$s->send($r);config(['app.env'=>'production','mail_report.telehub_key'=>'']);$s->send($r);$this->assertSame('telehub_configuration_required',$r->refresh()->error_code);$this->assertSame(0,(int)$r->attempts);Http::assertNothingSent();
|
||||
}
|
||||
public function test_authorization_failure_does_not_fallback_or_blindly_retry():void
|
||||
{
|
||||
Http::fake(['*/api/v1/messages'=>Http::response([],403)]);$s=app(DailyReportService::class);$r=$this->report();$s->send($r);$this->travel(1)->hours();$s->send($r);$this->assertSame('failed',$r->refresh()->status);$this->assertSame('telehub_http_403',$r->error_code);Http::assertSentCount(1);
|
||||
}
|
||||
public function test_uncertain_receipt_is_terminal_and_never_reposted():void
|
||||
{
|
||||
$this->fake('uncertain');$s=app(DailyReportService::class);$r=$this->report();$s->send($r);$this->travel(1)->hours();$s->send($r);$this->assertSame('uncertain',$r->refresh()->status);Http::assertSentCount(1);
|
||||
}
|
||||
public function test_rate_limit_retains_key_and_obeys_retry_after():void
|
||||
{
|
||||
Http::fake(['*/api/v1/messages'=>Http::sequence()->push([],429,['Retry-After'=>'900'])->push(['data'=>['id'=>self::UUID,'status'=>'queued']],202)]);$s=app(DailyReportService::class);$r=$this->report();$s->send($r);$key=$r->refresh()->summary['_telehub']['key'];$this->travel(6)->minutes();$s->send($r);Http::assertSentCount(1);$this->travel(10)->minutes();$s->send($r);$this->assertSame('queued',$r->refresh()->status);Http::assertSent(fn($q)=>$q->hasHeader('Idempotency-Key',$key));
|
||||
}
|
||||
public function test_receipt_id_mismatch_keeps_original_receipt():void
|
||||
{
|
||||
$this->fake();$s=app(DailyReportService::class);$r=$this->report();$s->send($r);$this->travel(6)->minutes();Http::fake(['*/api/v1/messages*'=>Http::response(['data'=>['id'=>'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa','status'=>'sent']],200)]);$s->send($r);$this->assertSame(self::UUID,$r->refresh()->summary['_telehub']['receipt_id']);$this->assertSame('queued',$r->status);$this->assertSame('telehub_response_invalid',$r->error_code);
|
||||
}
|
||||
public function test_cross_instance_state_cannot_be_reused():void
|
||||
{
|
||||
$this->fake();$s=app(DailyReportService::class);$r=$this->report();$s->send($r);config(['mail_report.project'=>'HN']);$this->expectException(\RuntimeException::class);$s->send($r);
|
||||
}
|
||||
public function test_reporting_credentials_are_not_in_mailflow_public_settings():void
|
||||
{
|
||||
$settings=Settings::publicSettings();$this->assertArrayNotHasKey('telehub_key',$settings);$this->assertStringNotContainsString('private-report-key',json_encode($settings));
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user