From a83a4d767590c2731a6b536431bb37d76fd5ecdf Mon Sep 17 00:00:00 2001 From: codex Date: Mon, 2 Nov 2026 02:04:44 +0800 Subject: [PATCH] refactor(ticket): isolate post-commit notifications --- .../Controllers/Admin/TicketController.php | 20 +--- web/app/Controllers/UserController.php | 48 +-------- web/app/Services/Ticket/TicketEvent.php | 27 ++++++ .../Ticket/TicketNotificationDispatcher.php | 97 +++++++++++++++++++ .../Ticket/TicketNotificationReport.php | 13 +++ .../Ticket/TicketNotificationTransport.php | 21 ++++ .../TicketNotificationTransportAdapter.php | 28 ++++++ .../TicketNotificationDispatcherTest.php | 72 ++++++++++++++ .../TicketWorkflowCharacterizationTest.php | 5 +- 9 files changed, 269 insertions(+), 62 deletions(-) create mode 100644 web/app/Services/Ticket/TicketEvent.php create mode 100644 web/app/Services/Ticket/TicketNotificationDispatcher.php create mode 100644 web/app/Services/Ticket/TicketNotificationReport.php create mode 100644 web/app/Services/Ticket/TicketNotificationTransport.php create mode 100644 web/app/Services/Ticket/TicketNotificationTransportAdapter.php create mode 100644 web/tests/TicketNotificationDispatcherTest.php diff --git a/web/app/Controllers/Admin/TicketController.php b/web/app/Controllers/Admin/TicketController.php index 7f35e952..5e801457 100644 --- a/web/app/Controllers/Admin/TicketController.php +++ b/web/app/Controllers/Admin/TicketController.php @@ -4,7 +4,6 @@ namespace App\Controllers\Admin; use App\Models\Ticket; use App\Models\TicketAttachment; -use App\Models\User; use App\Services\Auth; use App\Services\AdminDataMasker; @@ -14,13 +13,12 @@ use App\Services\TicketTelegramNotifier; use App\Services\AdminCsrf; use App\Services\Ticket\ReplyTicketCommand; use App\Services\Ticket\TicketThreadService; +use App\Services\Ticket\TicketEvent; +use App\Services\Ticket\TicketNotificationDispatcher; use App\Services\Ticket\TicketReadModel; use App\Services\Ticket\TicketThreadQuery; use App\Services\Ticket\TicketViewer; -use App\Services\Mail; -use App\Services\Config; - use App\Utils\SafeDatatables as Datatables; use App\Utils\DatatablesHelper; @@ -120,19 +118,7 @@ class TicketController extends AdminController return $this->echoJson($response, ['ret' => 0, 'msg' => '工单不存在']); } - $ticketMain = $result->root; - try { - $user = User::where('id', (int) $ticketMain->userid)->first(); - if ($user !== null && trim((string) $user->email) !== '') { - Mail::send($user->email, Config::get('appName') . ' - 工单收到回复', 'ticket/replied.tpl', [ - 'user' => $user, - 'ticket' => $ticketMain, - 'ticket_url' => rtrim((string) Config::get('baseUrl'), '/') . '/user/ticket/' . (int) $ticketMain->id . '/view', - ], [], 'ticket_replied'); - } - } catch (\Throwable $exception) { - error_log('Ticket user notification failed: ' . $exception->getMessage()); - } + (new TicketNotificationDispatcher())->dispatch(TicketEvent::adminReply($result)); $res['ret'] = 1; $res['msg'] = "提交成功"; diff --git a/web/app/Controllers/UserController.php b/web/app/Controllers/UserController.php index dee761ea..8125532b 100644 --- a/web/app/Controllers/UserController.php +++ b/web/app/Controllers/UserController.php @@ -21,8 +21,6 @@ use App\Models\UserSurveyOption; use App\Models\UserSurveyQuestion; use App\Models\UserSurveyResponse; use App\Models\CheckoutApply; -use App\Services\Mail; -use App\Services\TicketTelegramNotifier; use App\Services\RedisClient; use App\Services\AdminCsrf; use App\Services\AccountSecurityService; @@ -35,6 +33,8 @@ use App\Services\TicketAttachmentService; use App\Services\Ticket\OpenTicketCommand; use App\Services\Ticket\ReplyTicketCommand; use App\Services\Ticket\TicketThreadService; +use App\Services\Ticket\TicketEvent; +use App\Services\Ticket\TicketNotificationDispatcher; use App\Services\Ticket\TicketQueueQuery; use App\Services\Ticket\TicketReadModel; use App\Services\Ticket\TicketThreadQuery; @@ -668,13 +668,7 @@ class UserController extends BaseController : '工单保存失败'; return $this->echoJson($response, ['ret' => 0, 'msg' => $message]); } - try { - // The ticket is already committed; notification failure must not - // make the client retry and create a duplicate thread. - $this->notifyTicketCreated($result->root); - } catch (\Throwable $exception) { - error_log('Ticket creation notification failed: ' . $exception->getMessage()); - } + (new TicketNotificationDispatcher())->dispatch(TicketEvent::created($result)); return $this->echoJson($response, ['ret' => 1, 'msg' => '提交成功']); } @@ -710,14 +704,7 @@ class UserController extends BaseController if ($result === null) { return $this->echoJson($response, ['ret' => 0, 'msg' => '工单不存在']); } - try { - // Notifications are best-effort and deliberately happen only - // after the reply transaction has committed. A mail/Telegram - // outage must not make the client retry an already saved reply. - $this->notifyTicketAdmins($result->event, $result->root, $result->message->content); - } catch (\Throwable $exception) { - error_log('Ticket administrator notification failed: ' . $exception->getMessage()); - } + (new TicketNotificationDispatcher())->dispatch(TicketEvent::userReply($result)); return $this->echoJson($response, ['ret' => 1, 'msg' => '提交成功']); } @@ -761,33 +748,6 @@ class UserController extends BaseController return $this->streamTicketAttachment($response, $attachment); } - private function notifyTicketAdmins($event, $ticket, $content) - { - foreach (User::where('is_admin', 1)->get() as $admin) { - try { - Mail::send($admin->email, Config::get('appName') . ' - ' . $event, 'news/warn.tpl', [ - 'user' => $admin, 'text' => '工单 #' . (int) $ticket->id . ' 有新的消息,请在网站管理页面查看。', - ]); - } catch (\Throwable $exception) { - error_log('Ticket administrator email failed for ticket ' . (int) $ticket->id); - } - } - TicketTelegramNotifier::notify($event, (int) $ticket->id, $ticket->title, $content); - } - - private function notifyTicketCreated($ticket) - { - $url = rtrim((string) Config::get('baseUrl'), '/') . '/user/ticket/' . (int) $ticket->id . '/view'; - Mail::send($this->user->email, Config::get('appName') . ' - 工单已创建', 'ticket/created.tpl', [ - 'user' => $this->user, 'ticket' => $ticket, 'ticket_url' => $url, - ], [], 'ticket_created'); - try { - $this->notifyTicketAdmins('新工单', $ticket, $ticket->content); - } catch (\Throwable $exception) { - error_log('Ticket administrator notification failed: ' . $exception->getMessage()); - } - } - private function ticketInstances(): array { try { diff --git a/web/app/Services/Ticket/TicketEvent.php b/web/app/Services/Ticket/TicketEvent.php new file mode 100644 index 00000000..2294e709 --- /dev/null +++ b/web/app/Services/Ticket/TicketEvent.php @@ -0,0 +1,27 @@ +transport ??= new TicketNotificationTransportAdapter(); + } + + public function dispatch(TicketEvent $event): TicketNotificationReport + { + $root = $event->result->root; + $message = $event->result->message; + $owner = User::where('id', (int) $root->userid)->first(); + $jobs = []; + $appName = (string) Config::get('appName'); + $ticketUrl = rtrim((string) Config::get('baseUrl'), '/') + . '/user/ticket/' . (int) $root->id . '/view'; + + if ($event->kind === 'created' && $owner !== null && trim((string) $owner->email) !== '') { + $jobs[] = ['mail:owner', function () use ($owner, $root, $ticketUrl, $appName): void { + $this->transport->sendMail( + (string) $owner->email, + $appName . ' - 工单已创建', + 'ticket/created.tpl', + ['user' => $owner, 'ticket' => $root, 'ticket_url' => $ticketUrl], + 'ticket_created' + ); + }]; + } + + if (in_array($event->kind, ['created', 'user_reply'], true)) { + foreach (User::where('is_admin', 1)->get() as $admin) { + if (trim((string) $admin->email) === '') { + continue; + } + $jobs[] = ['mail:admin:' . (int) $admin->id, function () use ($admin, $root, $appName): void { + $this->transport->sendMail( + (string) $admin->email, + $appName . ' - ' . (string) $root->title, + 'news/warn.tpl', + [ + 'user' => $admin, + 'text' => '工单 #' . (int) $root->id . ' 有新的消息,请在网站管理页面查看。', + ] + ); + }]; + } + $jobs[] = ['telegram', function () use ($event, $root, $message): void { + $this->transport->sendTelegram( + $event->result->event, + (int) $root->id, + (string) $root->title, + (string) $message->content + ); + }]; + } + + if ($event->kind === 'admin_reply' && $owner !== null && trim((string) $owner->email) !== '') { + $jobs[] = ['mail:owner', function () use ($owner, $root, $ticketUrl, $appName): void { + $this->transport->sendMail( + (string) $owner->email, + $appName . ' - 工单收到回复', + 'ticket/replied.tpl', + ['user' => $owner, 'ticket' => $root, 'ticket_url' => $ticketUrl], + 'ticket_replied' + ); + }]; + } + + $succeeded = 0; + $errors = []; + foreach ($jobs as [$channel, $job]) { + try { + $job(); + $succeeded += 1; + } catch (\Throwable $exception) { + $errors[] = ['channel' => $channel, 'error' => $exception->getMessage()]; + error_log('Ticket notification failed [' . $channel . ']: ' . $exception->getMessage()); + } + } + return new TicketNotificationReport(count($jobs), $succeeded, $errors); + } +} diff --git a/web/app/Services/Ticket/TicketNotificationReport.php b/web/app/Services/Ticket/TicketNotificationReport.php new file mode 100644 index 00000000..cfcbf070 --- /dev/null +++ b/web/app/Services/Ticket/TicketNotificationReport.php @@ -0,0 +1,13 @@ +addConnection(['driver' => 'sqlite', 'database' => ':memory:'], 'default'); +$capsule->setAsGlobal(); +$capsule->bootEloquent(); +$GLOBALS['System_Config'] = ['baseUrl' => 'https://panel.example.test']; +$schema = $capsule->getConnection('default')->getSchemaBuilder(); +$schema->create('user', static function (Blueprint $table): void { + $table->increments('id'); + $table->string('user_name'); + $table->string('email'); + $table->boolean('is_admin')->default(false); +}); +Capsule::table('user')->insert([ + ['id' => 7, 'user_name' => 'customer', 'email' => 'owner@example.test', 'is_admin' => 0], + ['id' => 9, 'user_name' => 'admin-one', 'email' => 'admin1@example.test', 'is_admin' => 1], + ['id' => 10, 'user_name' => 'admin-two', 'email' => 'admin2@example.test', 'is_admin' => 1], +]); + +$root = new Ticket(); +$root->id = 44; +$root->userid = 7; +$root->title = 'Network issue'; +$root->content = 'Cannot connect'; +$root->rootid = 0; +$message = clone $root; +$result = new TicketWriteResult($root, $message, '新工单', []); + +$transport = new class implements TicketNotificationTransport { + public array $mail = []; + public array $telegram = []; + + public function sendMail(string $email, string $subject, string $template, array $data, ?string $event = null): void + { + $this->mail[] = compact('email', 'subject', 'template', 'data', 'event'); + if ($email === 'owner@example.test') { + throw new RuntimeException('mail outage'); + } + } + + public function sendTelegram(string $event, int $ticketId, string $title, string $content): void + { + $this->telegram[] = compact('event', 'ticketId', 'title', 'content'); + } +}; + +$report = (new TicketNotificationDispatcher($transport))->dispatch(TicketEvent::created($result)); +$assert(count($transport->mail) === 3, + 'A failed owner confirmation blocked administrator email delivery.'); +$assert(count($transport->telegram) === 1, + 'A failed email blocked the independent Telegram channel.'); +$assert($report->attempted === 4 && $report->succeeded === 3 && count($report->errors) === 1, + 'Notification report does not describe isolated channel outcomes.'); + +echo "Ticket notification isolation checks passed.\n"; diff --git a/web/tests/TicketWorkflowCharacterizationTest.php b/web/tests/TicketWorkflowCharacterizationTest.php index c884970f..b3b5ba54 100644 --- a/web/tests/TicketWorkflowCharacterizationTest.php +++ b/web/tests/TicketWorkflowCharacterizationTest.php @@ -83,12 +83,15 @@ $assert($first !== null && (int) $first->id === 1, $userController = file_get_contents(dirname(__DIR__) . '/app/Controllers/UserController.php'); $adminController = file_get_contents(dirname(__DIR__) . '/app/Controllers/Admin/TicketController.php'); $createTransaction = strpos($userController, '(new TicketThreadService())->open'); -$createNotification = strpos($userController, '$this->notifyTicketCreated($result->root)'); +$createNotification = strpos($userController, 'TicketEvent::created($result)'); $assert($createTransaction !== false && $createNotification !== false && $createTransaction < $createNotification, 'Ticket creation notifications are not visibly ordered after persistence.'); $assert(str_contains($adminController, 'generate(false)') && str_contains($adminController, "'statusTotals'"), 'The administrator queue no longer exposes server paging and complete totals.'); +$assert(!str_contains($userController, 'Mail::send') + && !str_contains($adminController, 'Mail::send'), + 'A ticket controller still owns post-commit notification delivery.'); echo "Ticket workflow characterization checks passed.\n";