171 lines
6.5 KiB
PHP
171 lines
6.5 KiB
PHP
<?php
|
||
|
||
namespace App\Console\Commands;
|
||
|
||
use DateTimeImmutable;
|
||
use Illuminate\Console\Command;
|
||
use Illuminate\Support\Facades\DB;
|
||
use Illuminate\Support\Facades\Http;
|
||
use RuntimeException;
|
||
use Throwable;
|
||
|
||
class SendCmbMailFailureNotification extends Command
|
||
{
|
||
protected $signature = 'cmb-mail:notify-failure
|
||
{--date= : 账单日期 YYYY-MM-DD;默认前一天}
|
||
{--type=unknown : 失败类型}
|
||
{--reason= : 已脱敏的简短失败原因}
|
||
{--recipient= : 接收人的钉钉企业昵称}
|
||
{--test : 发送通道测试消息}';
|
||
|
||
protected $description = '由生产服务器向指定钉钉成员发送招商银行邮件任务失败提醒';
|
||
|
||
public function handle(): int
|
||
{
|
||
try {
|
||
$date = $this->date();
|
||
$recipient = trim((string) $this->option('recipient'));
|
||
if ($recipient === '') {
|
||
throw new RuntimeException('未配置钉钉提醒接收人。');
|
||
}
|
||
|
||
$userIds = DB::table('dingtalk_identities')
|
||
->where('nickname', $recipient)
|
||
->whereNotNull('dingtalk_user_id')
|
||
->pluck('dingtalk_user_id')
|
||
->map(static fn ($value): string => trim((string) $value))
|
||
->filter()
|
||
->unique()
|
||
->values();
|
||
|
||
if ($userIds->count() !== 1) {
|
||
throw new RuntimeException(
|
||
$userIds->isEmpty()
|
||
? '没有找到对应的钉钉企业成员。'
|
||
: '该昵称对应多个钉钉企业成员,无法安全确定接收人。'
|
||
);
|
||
}
|
||
|
||
[$title, $text] = $this->message(
|
||
$date,
|
||
trim((string) $this->option('type')) ?: 'unknown',
|
||
$this->safeReason((string) $this->option('reason')),
|
||
(bool) $this->option('test'),
|
||
);
|
||
$this->sendToDingTalk([$userIds->first()], $title, $text);
|
||
$this->info($this->option('test') ? '钉钉通知通道测试已发送。' : '钉钉失败提醒已发送。');
|
||
|
||
return self::SUCCESS;
|
||
} catch (Throwable $exception) {
|
||
$this->error($exception->getMessage());
|
||
|
||
return self::FAILURE;
|
||
}
|
||
}
|
||
|
||
private function date(): string
|
||
{
|
||
$value = trim((string) $this->option('date'));
|
||
$value = $value !== '' ? $value : now('Asia/Shanghai')->subDay()->toDateString();
|
||
$parsed = DateTimeImmutable::createFromFormat('!Y-m-d', $value);
|
||
if (! $parsed || $parsed->format('Y-m-d') !== $value) {
|
||
throw new RuntimeException('--date 必须使用 YYYY-MM-DD 格式。');
|
||
}
|
||
|
||
return $value;
|
||
}
|
||
|
||
/** @return array{0:string,1:string} */
|
||
private function message(string $date, string $type, string $reason, bool $test): array
|
||
{
|
||
if ($test) {
|
||
return [
|
||
'招商银行邮件任务通知通道测试',
|
||
implode("\n", [
|
||
'### 招商银行邮件任务通知通道测试',
|
||
'- 接收方式:生产服务器直接发送至钉钉',
|
||
'- 用途:仅发送招商银行邮件任务异常提醒',
|
||
'- 结果:通道已接通',
|
||
]),
|
||
];
|
||
}
|
||
|
||
$labels = [
|
||
'auth' => '邮箱授权失效或登录失败',
|
||
'config' => '任务配置缺失',
|
||
'not_found' => '未找到当天招商银行账单邮件',
|
||
'download' => '账单下载失败',
|
||
'archive' => '账单解压或安全校验失败',
|
||
'import' => '银行账单导入失败',
|
||
'unknown' => '任务执行失败',
|
||
];
|
||
|
||
return [
|
||
'招商银行邮件任务失败',
|
||
implode("\n", [
|
||
'### 招商银行邮件任务失败',
|
||
'- 账单日期:' . $date,
|
||
'- 失败类型:' . ($labels[$type] ?? $labels['unknown']),
|
||
'- 执行结果:07:00、07:10 两次均失败',
|
||
'- 原因:' . $reason,
|
||
'请检查服务器任务日志及 163 邮箱授权状态。',
|
||
]),
|
||
];
|
||
}
|
||
|
||
private function safeReason(string $reason): string
|
||
{
|
||
$reason = preg_replace('/[\r\n\t]+/u', ' ', trim($reason)) ?? '';
|
||
$reason = preg_replace('/[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,}/iu', '[邮箱已隐藏]', $reason) ?? $reason;
|
||
$reason = mb_substr($reason, 0, 200);
|
||
|
||
return $reason !== '' ? $reason : '服务器日志已记录具体错误。';
|
||
}
|
||
|
||
/** @param list<string> $userIds */
|
||
private function sendToDingTalk(array $userIds, string $title, string $text): void
|
||
{
|
||
$clientId = trim((string) config('dingtalk.client_id'));
|
||
$clientSecret = trim((string) config('dingtalk.client_secret'));
|
||
$robotCode = trim((string) config('dingtalk.robot.code'));
|
||
if ($clientId === '' || $clientSecret === '' || $robotCode === '') {
|
||
throw new RuntimeException('钉钉应用通知凭据不完整。');
|
||
}
|
||
|
||
$timeout = max(3, min(30, (int) config('dingtalk.timeout', 10)));
|
||
$tokenResponse = Http::asJson()
|
||
->acceptJson()
|
||
->timeout($timeout)
|
||
->post((string) config('dingtalk.robot.access_token_url'), [
|
||
'appKey' => $clientId,
|
||
'appSecret' => $clientSecret,
|
||
]);
|
||
$accessToken = trim((string) $tokenResponse->json('accessToken'));
|
||
if (! $tokenResponse->successful() || $accessToken === '') {
|
||
throw new RuntimeException('钉钉应用访问令牌获取失败。');
|
||
}
|
||
|
||
$response = Http::asJson()
|
||
->acceptJson()
|
||
->withHeaders(['x-acs-dingtalk-access-token' => $accessToken])
|
||
->timeout($timeout)
|
||
->post((string) config('dingtalk.robot.send_url'), [
|
||
'robotCode' => $robotCode,
|
||
'userIds' => $userIds,
|
||
'msgKey' => 'sampleMarkdown',
|
||
'msgParam' => json_encode([
|
||
'title' => $title,
|
||
'text' => $text,
|
||
], JSON_UNESCAPED_UNICODE | JSON_THROW_ON_ERROR),
|
||
]);
|
||
|
||
if (! $response->successful()) {
|
||
$code = trim((string) $response->json('code'));
|
||
throw new RuntimeException(
|
||
'钉钉消息发送失败:HTTP ' . $response->status()
|
||
. ($code !== '' ? ' ' . mb_substr($code, 0, 120) : '')
|
||
);
|
||
}
|
||
}
|
||
}
|