From f97e935fc0ff4925755cda1869fab5aecfc37d35 Mon Sep 17 00:00:00 2001 From: codex Date: Mon, 2 Nov 2026 02:03:26 +0800 Subject: [PATCH] refactor(ticket): centralize thread mutations --- .../Controllers/Admin/TicketController.php | 18 +-- web/app/Controllers/UserController.php | 87 +++------- web/app/Services/Ticket/OpenTicketCommand.php | 17 ++ .../Services/Ticket/ReplyTicketCommand.php | 17 ++ .../Services/Ticket/TicketThreadService.php | 149 ++++++++++++++++++ web/app/Services/Ticket/TicketWriteResult.php | 17 ++ web/app/Services/TicketReplyService.php | 103 ------------ web/tests/TicketReplyTransactionTest.php | 59 +++++-- .../TicketWorkflowCharacterizationTest.php | 4 +- 9 files changed, 282 insertions(+), 189 deletions(-) create mode 100644 web/app/Services/Ticket/OpenTicketCommand.php create mode 100644 web/app/Services/Ticket/ReplyTicketCommand.php create mode 100644 web/app/Services/Ticket/TicketThreadService.php create mode 100644 web/app/Services/Ticket/TicketWriteResult.php delete mode 100644 web/app/Services/TicketReplyService.php diff --git a/web/app/Controllers/Admin/TicketController.php b/web/app/Controllers/Admin/TicketController.php index 0686368d..7f35e952 100644 --- a/web/app/Controllers/Admin/TicketController.php +++ b/web/app/Controllers/Admin/TicketController.php @@ -6,14 +6,14 @@ use App\Models\Ticket; use App\Models\TicketAttachment; use App\Models\User; -use voku\helper\AntiXSS; use App\Services\Auth; use App\Services\AdminDataMasker; use App\Services\AdminPermission; use App\Services\TicketTelegramConfig; use App\Services\TicketTelegramNotifier; -use App\Services\TicketReplyService; use App\Services\AdminCsrf; +use App\Services\Ticket\ReplyTicketCommand; +use App\Services\Ticket\TicketThreadService; use App\Services\Ticket\TicketReadModel; use App\Services\Ticket\TicketThreadQuery; use App\Services\Ticket\TicketViewer; @@ -97,16 +97,16 @@ class TicketController extends AdminController return $this->echoJson($response, $res); } - $antiXss = new AntiXSS(); - $cleanContent = $antiXss->xss_clean($content); try { - $result = TicketReplyService::create( + $result = (new TicketThreadService())->reply(new ReplyTicketCommand( (int) $id, (int) Auth::getUser()->id, - $cleanContent, + $content, (int) $status, - $request - ); + $request, + null, + true + )); } catch (\Throwable $exception) { error_log('Admin ticket reply failed: ' . $exception->getMessage()); return $this->echoJson($response, [ @@ -120,7 +120,7 @@ class TicketController extends AdminController return $this->echoJson($response, ['ret' => 0, 'msg' => '工单不存在']); } - $ticketMain = $result['root']; + $ticketMain = $result->root; try { $user = User::where('id', (int) $ticketMain->userid)->first(); if ($user !== null && trim((string) $user->email) !== '') { diff --git a/web/app/Controllers/UserController.php b/web/app/Controllers/UserController.php index 1b7c11d3..dee761ea 100644 --- a/web/app/Controllers/UserController.php +++ b/web/app/Controllers/UserController.php @@ -13,8 +13,6 @@ use App\Utils\Hash; use App\Utils\Totp; use App\Utils\Tools; -use voku\helper\AntiXSS; - use App\Models\User; use App\Models\Configurations; use App\Models\Code; @@ -34,7 +32,9 @@ use App\Services\Payment\UsdtConfig; use App\Services\Payment\YipayConfig; use App\Services\Payment\PaytaroConfig; use App\Services\TicketAttachmentService; -use App\Services\TicketReplyService; +use App\Services\Ticket\OpenTicketCommand; +use App\Services\Ticket\ReplyTicketCommand; +use App\Services\Ticket\TicketThreadService; use App\Services\Ticket\TicketQueueQuery; use App\Services\Ticket\TicketReadModel; use App\Services\Ticket\TicketThreadQuery; @@ -641,44 +641,27 @@ class UserController extends BaseController } $title = $request->getParam('title'); $content = $request->getParam('content'); - $ticketType = $this->ticketType($request->getParam('ticket_type')); - $priority = $this->ticketPriority($request->getParam('priority')); - $instanceId = $this->ticketInstanceId($request->getParam('instance_id')); $instanceInput = $request->getParam('instance_id'); - if ($instanceInput !== null && $instanceInput !== '' && $instanceId === null) { + if ($instanceInput !== null && $instanceInput !== '' + && (!is_scalar($instanceInput) || !ctype_digit((string) $instanceInput))) { return $this->echoJson($response, ['ret' => 0, 'msg' => '关联实例不存在或无权访问']); } if (!is_string($title) || !is_string($content) || trim($title) === '' || trim($content) === '') { return $this->echoJson($response, ['ret' => 0, 'msg' => '请填全工单主题和内容']); } - $cleaner = new AntiXSS(); - $ticket = new Ticket(); - $ticket->title = $cleaner->xss_clean($title); - $ticket->content = $cleaner->xss_clean($content); - $ticket->rootid = 0; - $ticket->userid = $this->user->id; - $ticket->datetime = time(); - $ticket->status = 1; - $ticket->ticket_type = $ticketType; - $ticket->priority = $priority; - $ticket->instance_id = $instanceId; - $connection = $ticket->getConnection(); - $createdPaths = []; try { - $connection->transaction(function () use ($ticket, $request, &$createdPaths) { - if (!$ticket->save()) { - throw new \RuntimeException('工单保存失败'); - } - TicketAttachmentService::store( - $request, - (int) $ticket->id, - (int) $ticket->id, - (int) $this->user->id, - $createdPaths - ); - }, 1); + $result = (new TicketThreadService())->open(new OpenTicketCommand( + (int) $this->user->id, + $title, + $content, + is_scalar($request->getParam('ticket_type')) + ? (string) $request->getParam('ticket_type') : '', + is_scalar($request->getParam('priority')) + ? (string) $request->getParam('priority') : '', + $instanceInput === null || $instanceInput === '' ? null : (int) $instanceInput, + $request + )); } catch (\Throwable $exception) { - TicketAttachmentService::discardPaths($createdPaths); error_log('Ticket creation failed: ' . $exception->getMessage()); $message = $exception instanceof \InvalidArgumentException ? $exception->getMessage() @@ -688,7 +671,7 @@ class UserController extends BaseController try { // The ticket is already committed; notification failure must not // make the client retry and create a duplicate thread. - $this->notifyTicketCreated($ticket); + $this->notifyTicketCreated($result->root); } catch (\Throwable $exception) { error_log('Ticket creation notification failed: ' . $exception->getMessage()); } @@ -706,16 +689,15 @@ class UserController extends BaseController if (!is_string($content) || trim($content) === '' || !in_array((string) $status, ['0', '1'], true)) { return $this->echoJson($response, ['ret' => 0, 'msg' => '请填全']); } - $cleanContent = (new AntiXSS())->xss_clean($content); try { - $result = TicketReplyService::create( + $result = (new TicketThreadService())->reply(new ReplyTicketCommand( (int) $args['id'], (int) $this->user->id, - $cleanContent, + $content, (int) $status, $request, (int) $this->user->id - ); + )); } catch (\Throwable $exception) { error_log('User ticket reply failed: ' . $exception->getMessage()); return $this->echoJson($response, [ @@ -732,7 +714,7 @@ class UserController extends BaseController // 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['reply']->content); + $this->notifyTicketAdmins($result->event, $result->root, $result->message->content); } catch (\Throwable $exception) { error_log('Ticket administrator notification failed: ' . $exception->getMessage()); } @@ -816,33 +798,6 @@ class UserController extends BaseController } } - private function ticketType($value): string - { - $value = is_scalar($value) ? (string) $value : ''; - return in_array($value, ['pre_sales', 'after_sales', 'technical', 'finance'], true) - ? $value : 'technical'; - } - - private function ticketPriority($value): string - { - $value = is_scalar($value) ? (string) $value : ''; - return in_array($value, ['high', 'medium', 'low'], true) ? $value : 'medium'; - } - - private function ticketInstanceId($value): ?int - { - if (!is_scalar($value) || $value === null || $value === '' || !ctype_digit((string) $value)) { - return null; - } - try { - $instance = CloudInstance::where('id', (int) $value)->where('user_id', (int) $this->user->id) - ->where('status', '<>', 'deleted')->first(); - return $instance === null ? null : (int) $instance->id; - } catch (\Throwable $exception) { - return null; - } - } - protected function streamTicketAttachment($response, $attachment) { if (!$attachment instanceof TicketAttachment) { diff --git a/web/app/Services/Ticket/OpenTicketCommand.php b/web/app/Services/Ticket/OpenTicketCommand.php new file mode 100644 index 00000000..3422a31e --- /dev/null +++ b/web/app/Services/Ticket/OpenTicketCommand.php @@ -0,0 +1,17 @@ +cleanRequired($command->title, '请填全工单主题和内容'); + $content = $this->cleanRequired($command->content, '请填全工单主题和内容'); + $type = in_array($command->type, ['pre_sales', 'after_sales', 'technical', 'finance'], true) + ? $command->type : 'technical'; + $priority = in_array($command->priority, ['high', 'medium', 'low'], true) + ? $command->priority : 'medium'; + $instanceId = $this->ownedInstanceId($command->actorId, $command->instanceId); + + $connection = (new Ticket())->getConnection(); + $createdPaths = []; + try { + return $connection->transaction(function () use ( + $command, + $title, + $content, + $type, + $priority, + $instanceId, + &$createdPaths + ): TicketWriteResult { + $ticket = new Ticket(); + $ticket->title = $title; + $ticket->content = $content; + $ticket->rootid = 0; + $ticket->userid = $command->actorId; + $ticket->datetime = time(); + $ticket->status = 1; + $ticket->ticket_type = $type; + $ticket->priority = $priority; + $ticket->instance_id = $instanceId; + if (!$ticket->save()) { + throw new \RuntimeException('工单保存失败'); + } + $attachments = TicketAttachmentService::store( + $command->request, + (int) $ticket->id, + (int) $ticket->id, + $command->actorId, + $createdPaths + ); + return new TicketWriteResult($ticket, $ticket, '新工单', $attachments); + }, 1); + } catch (\Throwable $exception) { + TicketAttachmentService::discardPaths($createdPaths); + throw $exception; + } + } + + public function reply(ReplyTicketCommand $command): ?TicketWriteResult + { + if (!in_array($command->status, [0, 1], true)) { + throw new \InvalidArgumentException('工单状态无效'); + } + $content = $this->cleanRequired($command->content, '请填写回复内容'); + $connection = (new Ticket())->getConnection(); + $createdPaths = []; + try { + return $connection->transaction(function () use ( + $command, + $content, + &$createdPaths + ): ?TicketWriteResult { + $query = Ticket::where('id', $command->ticketId)->where('rootid', 0); + if ($command->ownerId !== null) { + $query->where('userid', $command->ownerId); + } + $root = $query->lockForUpdate()->first(); + if ($root === null) { + return null; + } + + $event = $command->status === 1 && (int) $root->status !== 1 + ? '工单重新开启' + : ($command->actorIsAdmin ? '管理员回复工单' : '用户回复工单'); + $reply = new Ticket(); + $reply->title = (string) $root->title; + $reply->content = $content; + $reply->rootid = (int) $root->id; + $reply->userid = $command->actorId; + $reply->datetime = time(); + $reply->status = $command->status; + $reply->ticket_type = (string) $root->ticket_type; + $reply->priority = (string) $root->priority; + $reply->instance_id = $root->instance_id; + + $root->status = $command->status; + if (!$root->save() || !$reply->save()) { + throw new \RuntimeException('工单回复保存失败'); + } + $attachments = TicketAttachmentService::store( + $command->request, + (int) $root->id, + (int) $reply->id, + $command->actorId, + $createdPaths + ); + return new TicketWriteResult($root, $reply, $event, $attachments); + }, 1); + } catch (\Throwable $exception) { + TicketAttachmentService::discardPaths($createdPaths); + throw $exception; + } + } + + private function cleanRequired(string $value, string $message): string + { + if (trim($value) === '') { + throw new \InvalidArgumentException($message); + } + $clean = trim((string) (new AntiXSS())->xss_clean($value)); + if ($clean === '') { + throw new \InvalidArgumentException($message); + } + return $clean; + } + + private function ownedInstanceId(int $userId, ?int $instanceId): ?int + { + if ($instanceId === null) { + return null; + } + $instance = CloudInstance::where('id', $instanceId)->where('user_id', $userId) + ->where('status', '<>', 'deleted')->first(); + if ($instance === null) { + throw new \InvalidArgumentException('关联实例不存在或无权访问'); + } + return (int) $instance->id; + } +} diff --git a/web/app/Services/Ticket/TicketWriteResult.php b/web/app/Services/Ticket/TicketWriteResult.php new file mode 100644 index 00000000..13058601 --- /dev/null +++ b/web/app/Services/Ticket/TicketWriteResult.php @@ -0,0 +1,17 @@ +getConnection(); - $createdPaths = []; - try { - return $connection->transaction(function () use ( - $ticketId, - $actorId, - $content, - $status, - $request, - $ownerId, - &$createdPaths - ) { - // This query must be inside the transaction. A lock acquired - // in autocommit mode would be released before the reply save. - $query = Ticket::where('id', $ticketId)->where('rootid', 0); - if ($ownerId !== null) { - $query->where('userid', $ownerId); - } - $root = $query->lockForUpdate()->first(); - if ($root === null) { - return null; - } - - $event = $status === 1 && (int) $root->status !== 1 - ? '工单重新开启' - : '用户回复工单'; - - $reply = new Ticket(); - $reply->title = (string) $root->title; - $reply->content = $content; - $reply->rootid = (int) $root->id; - $reply->userid = $actorId; - $reply->datetime = time(); - $reply->status = $status; - $reply->ticket_type = (string) $root->ticket_type; - $reply->priority = (string) $root->priority; - $reply->instance_id = $root->instance_id; - - $root->status = $status; - if (!$root->save() || !$reply->save()) { - throw new \RuntimeException('工单回复保存失败'); - } - - // Keep attachment rows in this transaction. The service also - // records every newly-created path for commit-failure cleanup. - $attachments = TicketAttachmentService::store( - $request, - (int) $root->id, - (int) $reply->id, - $actorId, - $createdPaths - ); - - return [ - 'root' => $root, - 'reply' => $reply, - 'event' => $event, - 'attachments' => $attachments, - ]; - }, 1); - } catch (\Throwable $exception) { - // The DB transaction has already rolled back (or failed to - // commit) when control reaches here. Only remove files created by - // this request; never delete pre-existing ticket attachments. - TicketAttachmentService::discardPaths($createdPaths); - throw $exception; - } - } -} diff --git a/web/tests/TicketReplyTransactionTest.php b/web/tests/TicketReplyTransactionTest.php index fc7ec5cc..2b28f22e 100644 --- a/web/tests/TicketReplyTransactionTest.php +++ b/web/tests/TicketReplyTransactionTest.php @@ -6,8 +6,10 @@ // same failure boundary. require dirname(__DIR__) . '/vendor/autoload.php'; -use App\Services\TicketReplyService; use App\Services\TicketAttachmentService; +use App\Services\Ticket\OpenTicketCommand; +use App\Services\Ticket\ReplyTicketCommand; +use App\Services\Ticket\TicketThreadService; use Illuminate\Database\Capsule\Manager as Capsule; use Illuminate\Database\Schema\Blueprint; @@ -55,6 +57,13 @@ $schema->create('ticket_attachments', static function (Blueprint $table): void { $table->string('sha256'); $table->integer('created_at'); }); +$schema->create('cloud_instances', static function (Blueprint $table): void { + $table->increments('id'); + $table->integer('user_id'); + $table->string('status'); +}); + +$service = new TicketThreadService(); Capsule::table('ticket')->insert([ 'id' => 1, @@ -96,7 +105,9 @@ $request = static function (array $files): object { // A user may only mutate a thread that they own. The missing result is the // public behavior used by the HTTP adapter to return "ticket not found" // without revealing another user's ticket. -$foreignResult = TicketReplyService::create(1, 8, 'must not be saved', 0, $request([]), 8); +$foreignResult = $service->reply(new ReplyTicketCommand( + 1, 8, 'must not be saved', 0, $request([]), 8 +)); $assert($foreignResult === null, 'A foreign user was able to reply to the ticket.'); $assert(Capsule::table('ticket')->where('rootid', 1)->count() === 0, 'The rejected foreign reply wrote a message row.'); @@ -113,7 +124,9 @@ $second = [ 'size' => filesize($secondPath), 'type' => 'image/png', ]; try { - TicketReplyService::create(1, 7, 'reply that must roll back', 0, $request([$first, $second]), 7); + $service->reply(new ReplyTicketCommand( + 1, 7, 'reply that must roll back', 0, $request([$first, $second]), 7 + )); throw new RuntimeException('Invalid attachment unexpectedly succeeded.'); } catch (InvalidArgumentException $exception) { // Expected validation failure; the assertions below verify the rollback. @@ -128,8 +141,10 @@ $assert(glob(BASE_PATH . '/storage/ticket-attachments/*') === [], 'A partially stored attachment file survived rollback.'); @unlink($secondPath); -$result = TicketReplyService::create(1, 7, 'successful reply', 0, $request([$uploaded('ok.png', $png)]), 7); -$assert(is_array($result) && $result['reply']->rootid == 1, 'Successful reply was not created.'); +$result = $service->reply(new ReplyTicketCommand( + 1, 7, 'successful reply', 0, $request([$uploaded('ok.png', $png)]), 7 +)); +$assert($result !== null && $result->message->rootid == 1, 'Successful reply was not created.'); $assert((int) Capsule::table('ticket')->where('id', 1)->value('status') === 0, 'Root status was not updated by a successful reply.'); $assert(Capsule::table('ticket')->where('rootid', 1)->count() === 1, @@ -144,14 +159,14 @@ $assert(is_file(BASE_PATH . '/storage/ticket-attachments/' . $attachment->storag // Closing and reopening are observable thread behaviors. Reopening a closed // thread has its own event so notification adapters can explain the change. -$reopened = TicketReplyService::create(1, 7, 'reopen', 1, $request([]), 7); -$assert(is_array($reopened) && $reopened['event'] === '工单重新开启', +$reopened = $service->reply(new ReplyTicketCommand(1, 7, 'reopen', 1, $request([]), 7)); +$assert($reopened !== null && $reopened->event === '工单重新开启', 'A closed ticket did not emit the reopen event.'); $assert((int) Capsule::table('ticket')->where('id', 1)->value('status') === 1, 'The reopened ticket root is not open.'); // The lock must be acquired in the transaction, not by a preflight query. -$serviceSource = file_get_contents(dirname(__DIR__) . '/app/Services/TicketReplyService.php'); +$serviceSource = file_get_contents(dirname(__DIR__) . '/app/Services/Ticket/TicketThreadService.php'); $assert(str_contains($serviceSource, 'transaction(function') && str_contains($serviceSource, 'lockForUpdate()->first()') && str_contains($serviceSource, 'TicketAttachmentService::store'), @@ -165,11 +180,37 @@ foreach ([ dirname(__DIR__) . '/app/Controllers/Admin/TicketController.php', ] as $controllerPath) { $controllerSource = file_get_contents($controllerPath); - $assert(str_contains($controllerSource, 'TicketReplyService::create') + $assert(str_contains($controllerSource, 'TicketThreadService') && !str_contains($controllerSource, '$previousStatus'), 'A ticket controller still uses the stale-status compensation flow.'); } +Capsule::table('cloud_instances')->insert(['id' => 31, 'user_id' => 7, 'status' => 'running']); +$opened = $service->open(new OpenTicketCommand( + 7, + 'Provisioning issue', + 'Cannot boot', + 'technical', + 'high', + 31, + $request([]) +)); +$assert($opened->root->rootid == 0 && $opened->message->id === $opened->root->id, + 'Opening a ticket did not create the root thread message.'); +$assert((int) $opened->root->instance_id === 31, + 'Opening a ticket lost the owned instance association.'); +$assert(!str_contains((string) $opened->root->content, '