refactor(ticket): isolate post-commit notifications

go
codex 3 weeks ago
parent f97e935fc0
commit a83a4d7675

@ -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'] = "提交成功";

@ -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 {

@ -0,0 +1,27 @@
<?php
namespace App\Services\Ticket;
final readonly class TicketEvent
{
private function __construct(
public string $kind,
public TicketWriteResult $result
) {
}
public static function created(TicketWriteResult $result): self
{
return new self('created', $result);
}
public static function userReply(TicketWriteResult $result): self
{
return new self('user_reply', $result);
}
public static function adminReply(TicketWriteResult $result): self
{
return new self('admin_reply', $result);
}
}

@ -0,0 +1,97 @@
<?php
namespace App\Services\Ticket;
use App\Models\User;
use App\Services\Config;
/**
* Delivers post-commit ticket notifications with channel isolation.
*
* Each recipient and Telegram are independent attempts. A failed transport is
* reported and logged but never changes the already-committed ticket result or
* prevents the remaining channels from running.
*/
final class TicketNotificationDispatcher
{
public function __construct(
private ?TicketNotificationTransport $transport = null
) {
$this->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);
}
}

@ -0,0 +1,13 @@
<?php
namespace App\Services\Ticket;
final readonly class TicketNotificationReport
{
public function __construct(
public int $attempted,
public int $succeeded,
public array $errors
) {
}
}

@ -0,0 +1,21 @@
<?php
namespace App\Services\Ticket;
interface TicketNotificationTransport
{
public function sendMail(
string $email,
string $subject,
string $template,
array $data,
?string $event = null
): void;
public function sendTelegram(
string $event,
int $ticketId,
string $title,
string $content
): void;
}

@ -0,0 +1,28 @@
<?php
namespace App\Services\Ticket;
use App\Services\Mail;
use App\Services\TicketTelegramNotifier;
final class TicketNotificationTransportAdapter implements TicketNotificationTransport
{
public function sendMail(
string $email,
string $subject,
string $template,
array $data,
?string $event = null
): void {
Mail::send($email, $subject, $template, $data, [], $event);
}
public function sendTelegram(
string $event,
int $ticketId,
string $title,
string $content
): void {
TicketTelegramNotifier::notify($event, $ticketId, $title, $content);
}
}

@ -0,0 +1,72 @@
<?php
require dirname(__DIR__) . '/vendor/autoload.php';
use App\Models\Ticket;
use App\Services\Ticket\TicketEvent;
use App\Services\Ticket\TicketNotificationDispatcher;
use App\Services\Ticket\TicketNotificationTransport;
use App\Services\Ticket\TicketWriteResult;
use Illuminate\Database\Capsule\Manager as Capsule;
use Illuminate\Database\Schema\Blueprint;
$assert = static function ($condition, string $message): void {
if (!$condition) {
throw new RuntimeException($message);
}
};
$capsule = new Capsule();
$capsule->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";

@ -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";

Loading…
Cancel
Save