From 281c36e9901c0d9b1fdade8ca6cbadbdce2176aa Mon Sep 17 00:00:00 2001 From: codex Date: Mon, 2 Nov 2026 02:02:10 +0800 Subject: [PATCH] refactor(ticket): centralize thread read projections --- .../Controllers/Admin/TicketController.php | 69 ++------ web/app/Controllers/UserController.php | 77 +++------ web/app/Models/Ticket.php | 21 --- web/app/Services/Ticket/TicketQueueQuery.php | 15 ++ web/app/Services/Ticket/TicketReadModel.php | 153 ++++++++++++++++++ web/app/Services/Ticket/TicketThreadQuery.php | 17 ++ web/app/Services/Ticket/TicketViewer.php | 23 +++ web/app/Services/TicketAttachmentService.php | 11 -- .../views/venix/admin/ticket/view.tpl | 4 +- .../views/venix/user/ticket_view.tpl | 14 +- web/tests/AdminTicketPrivacyContractTest.php | 7 +- web/tests/AdminTicketQueueContractTest.php | 6 +- web/tests/TicketReadModelTest.php | 107 ++++++++++++ 13 files changed, 370 insertions(+), 154 deletions(-) create mode 100644 web/app/Services/Ticket/TicketQueueQuery.php create mode 100644 web/app/Services/Ticket/TicketReadModel.php create mode 100644 web/app/Services/Ticket/TicketThreadQuery.php create mode 100644 web/app/Services/Ticket/TicketViewer.php create mode 100644 web/tests/TicketReadModelTest.php diff --git a/web/app/Controllers/Admin/TicketController.php b/web/app/Controllers/Admin/TicketController.php index fcc0115f..0686368d 100644 --- a/web/app/Controllers/Admin/TicketController.php +++ b/web/app/Controllers/Admin/TicketController.php @@ -14,6 +14,9 @@ use App\Services\TicketTelegramConfig; use App\Services\TicketTelegramNotifier; use App\Services\TicketReplyService; use App\Services\AdminCsrf; +use App\Services\Ticket\TicketReadModel; +use App\Services\Ticket\TicketThreadQuery; +use App\Services\Ticket\TicketViewer; use App\Services\Mail; use App\Services\Config; @@ -145,57 +148,33 @@ class TicketController extends AdminController public function show($request, $response, $args) { $id = (int) ($args['id'] ?? 0); - $ticketMain = Ticket::where("id", $id)->where("rootid", 0)->first(); - if ($ticketMain === null) { - return $response->withStatus(404); - } - $pageNum = 1; if (isset($request->getQueryParams()["page"])) { $pageNum = max(1, (int) $request->getQueryParams()["page"]); } - $ticketset=Ticket::where("id", $id)->orWhere("rootid", "=", $id)->orderBy("datetime", "desc")->paginate(5, ['*'], 'page', $pageNum); - $ticketset->setPath('/admin/ticket/'.$id."/view"); - $canViewAttachments = AdminPermission::isSuperAdmin() - && $this->ticketAttachmentsAvailable(); - foreach ($ticketset as $ticket) { - $author = User::find((int) $ticket->userid); - $isAdmin = $author != null && (int) $author->is_admin === 1; - $ticket->setAttribute('display_author_is_admin', $isAdmin); - $ticket->setAttribute( - 'display_author_name', - $author == null - ? '用户已删除' - : ($isAdmin ? '管理员' : AdminDataMasker::account($author->user_name)) - ); - $ticket->setAttribute('display_content', AdminDataMasker::sensitiveText($ticket->content)); - $attachments = []; - if ($canViewAttachments) { - try { - $attachments = TicketAttachment::where('message_id', (int) $ticket->id)->orderBy('id')->get(); - } catch (\Throwable $exception) { - // A partially migrated installation must still be able to open a ticket. - $attachments = []; - } - } - $ticket->setAttribute('attachments', $attachments); - $ticket->setAttribute('has_attachments', count($attachments) > 0); + $isSuperAdmin = AdminPermission::isSuperAdmin(); + $thread = (new TicketReadModel())->thread( + new TicketThreadQuery($id, $pageNum, 5), + TicketViewer::administrator((int) Auth::getUser()->id, $isSuperAdmin) + ); + if ($thread === null) { + return $response->withStatus(404); } + $ticketMain = $thread['root']; + $ticketset = $thread['messages']; + $ticketset->setPath('/admin/ticket/'.$id."/view"); return $this->view()->assign('ticketset', $ticketset) ->assign('ticket_main', $ticketMain) - ->assign('ticket_display_title', AdminDataMasker::sensitiveText((string) $ticketMain->title)) + ->assign('ticket_display_title', $thread['title']) ->assign('id', $id) - ->assign('ticket_can_view_attachments', $canViewAttachments) + ->assign('ticket_can_view_attachments', $isSuperAdmin) ->display('admin/ticket/view.tpl'); } public function attachment($request, $response, $args) { - if (!$this->ticketAttachmentsAvailable()) { - return $response->withStatus(404); - } try { $ticket = Ticket::where('id', (int) ($args['id'] ?? 0))->where('rootid', 0)->first(); $attachment = TicketAttachment::where('id', (int) ($args['attachment_id'] ?? 0)) @@ -264,24 +243,6 @@ class TicketController extends AdminController return $response->withHeader('Content-Type', 'application/json; charset=utf-8'); } - private function ticketAttachmentsAvailable(): bool - { - try { - $schema = (new TicketAttachment())->getConnection()->getSchemaBuilder(); - if (!$schema->hasTable('ticket_attachments')) { - return false; - } - foreach (['id', 'ticket_id', 'message_id', 'user_id', 'storage_key', 'original_name', 'mime_type', 'bytes', 'sha256', 'created_at'] as $column) { - if (!$schema->hasColumn('ticket_attachments', $column)) { - return false; - } - } - return true; - } catch (\Throwable $exception) { - return false; - } - } - private function ticketColumnExpression($schema, string $column, string $fallback): string { try { diff --git a/web/app/Controllers/UserController.php b/web/app/Controllers/UserController.php index 67fa78bf..1b7c11d3 100644 --- a/web/app/Controllers/UserController.php +++ b/web/app/Controllers/UserController.php @@ -35,6 +35,10 @@ use App\Services\Payment\YipayConfig; use App\Services\Payment\PaytaroConfig; use App\Services\TicketAttachmentService; use App\Services\TicketReplyService; +use App\Services\Ticket\TicketQueueQuery; +use App\Services\Ticket\TicketReadModel; +use App\Services\Ticket\TicketThreadQuery; +use App\Services\Ticket\TicketViewer; use App\Services\UserDrawerService; /** @@ -609,19 +613,16 @@ class UserController extends BaseController if (isset($request->getQueryParams()["page"])) { $pageNum = max(1, (int) $request->getQueryParams()["page"]); } - $openTickets = Ticket::where("userid", $this->user->id)->where("rootid", 0)->where("status", 1)->count(); - $closedTickets = Ticket::where("userid", $this->user->id)->where("rootid", 0)->where("status", 0)->count(); - $tickets = Ticket::where("userid", $this->user->id)->where("rootid", 0) - ->selectRaw('ticket.*, COALESCE((SELECT MAX(ticket_replies.datetime) ' - . 'FROM ticket AS ticket_replies WHERE ticket_replies.rootid = ticket.id), ' - . 'ticket.datetime) AS last_activity_at') - ->orderByDesc('last_activity_at')->orderByDesc('id') - ->paginate(15, ['*'], 'page', $pageNum); + $queue = (new TicketReadModel())->queue( + new TicketQueueQuery($pageNum, 15), + TicketViewer::user((int) $this->user->id) + ); + $tickets = $queue['tickets']; $tickets->setPath('/user/ticket'); return $this->view()->assign('tickets', $tickets) - ->assign('openTickets', $openTickets) - ->assign('closedTickets', $closedTickets) + ->assign('openTickets', $queue['open_count']) + ->assign('closedTickets', $queue['closed_count']) ->assign("cdn", $this->cdn) ->assign("backup_cdn", $this->backup_cdn) ->display('user/ticket.tpl'); @@ -741,46 +742,32 @@ class UserController extends BaseController public function ticket_view($request, $response, $args) { - $id = $args['id']; - $ticket_main = Ticket::where("id", "=", $id)->where("rootid", "=", 0)->first(); - if ($ticket_main == null || $ticket_main->userid != $this->user->id) { + $id = (int) ($args['id'] ?? 0); + $pageNum = isset($request->getQueryParams()['page']) + ? max(1, (int) $request->getQueryParams()['page']) + : 1; + $thread = (new TicketReadModel())->thread( + new TicketThreadQuery($id, $pageNum, 8), + TicketViewer::user((int) $this->user->id) + ); + if ($thread === null) { $newResponse = $response->withStatus(302)->withHeader('Location', '/user/ticket'); return $newResponse; } - - $pageNum = 1; - if (isset($request->getQueryParams()["page"])) { - $pageNum = $request->getQueryParams()["page"]; - } - - $ticketset = Ticket::where("id", $id)->orWhere("rootid", "=", $id)->orderBy("datetime", "desc")->paginate(8, ['*'], 'page', $pageNum); - $attachmentsAvailable = $this->ticketAttachmentsAvailable(); - foreach ($ticketset as $message) { - $attachments = []; - if ($attachmentsAvailable) { - try { - $attachments = TicketAttachment::where('message_id', (int) $message->id)->orderBy('id')->get(); - } catch (\Throwable $exception) { - $attachments = []; - } - } - $message->setAttribute('attachments', $attachments); - $message->setAttribute('has_attachments', count($attachments) > 0); - } + $ticket_main = $thread['root']; + $ticketset = $thread['messages']; $ticketset->setPath('/user/ticket/' . $id . "/view"); return $this->view()->assign('ticketset', $ticketset) ->assign('ticket_status', $ticket_main->status) ->assign('ticket_main', $ticket_main) + ->assign('ticket_display_title', $thread['title']) ->assign("id", $id) ->display('user/ticket_view.tpl'); } public function ticket_attachment($request, $response, $args) { - if (!$this->ticketAttachmentsAvailable()) { - return $response->withStatus(404); - } try { $ticket = Ticket::where('id', (int) ($args['id'] ?? 0))->where('rootid', 0) ->where('userid', (int) $this->user->id)->first(); @@ -874,24 +861,6 @@ class UserController extends BaseController return $response; } - private function ticketAttachmentsAvailable(): bool - { - try { - $schema = (new TicketAttachment())->getConnection()->getSchemaBuilder(); - if (!$schema->hasTable('ticket_attachments')) { - return false; - } - foreach (['id', 'ticket_id', 'message_id', 'user_id', 'storage_key', 'original_name', 'mime_type', 'bytes', 'sha256', 'created_at'] as $column) { - if (!$schema->hasColumn('ticket_attachments', $column)) { - return false; - } - } - return true; - } catch (\Throwable $exception) { - return false; - } - } - public function disable($request, $response, $args) { return $this->view()->display('user/disable.tpl'); diff --git a/web/app/Models/Ticket.php b/web/app/Models/Ticket.php index 7e1032dc..b2e7ee03 100644 --- a/web/app/Models/Ticket.php +++ b/web/app/Models/Ticket.php @@ -22,26 +22,5 @@ class Ticket extends Model return date("Y-m-d H:i:s", (int) $timestamp); } - public function User() - { - $user = User::where("id", $this->attributes['userid'])->first(); - return $user == null ? null : $user; - } - - public function authorName() - { - $user = $this->User(); - if ($user == null) { - return '用户已删除'; - } - - return $user->is_admin == 1 ? '管理员' : $user->user_name; - } - - public function authorIsAdmin() - { - $user = $this->User(); - return $user != null && $user->is_admin == 1; - } } diff --git a/web/app/Services/Ticket/TicketQueueQuery.php b/web/app/Services/Ticket/TicketQueueQuery.php new file mode 100644 index 00000000..be4faf57 --- /dev/null +++ b/web/app/Services/Ticket/TicketQueueQuery.php @@ -0,0 +1,15 @@ +page < 1 || $this->perPage < 1 || $this->perPage > 100) { + throw new \InvalidArgumentException('工单分页参数无效'); + } + } +} diff --git a/web/app/Services/Ticket/TicketReadModel.php b/web/app/Services/Ticket/TicketReadModel.php new file mode 100644 index 00000000..d2d2561c --- /dev/null +++ b/web/app/Services/Ticket/TicketReadModel.php @@ -0,0 +1,153 @@ +isAdmin) { + $roots->where('userid', $viewer->actorId); + } + + $counts = (clone $roots) + ->selectRaw('SUM(CASE WHEN status = 1 THEN 1 ELSE 0 END) AS open_count') + ->selectRaw('SUM(CASE WHEN status = 0 THEN 1 ELSE 0 END) AS closed_count') + ->first(); + $tickets = $roots + ->selectRaw('ticket.*, COALESCE((SELECT MAX(ticket_replies.datetime) ' + . 'FROM ticket AS ticket_replies WHERE ticket_replies.rootid = ticket.id), ' + . 'ticket.datetime) AS last_activity_at') + ->orderByDesc('last_activity_at')->orderByDesc('id') + ->paginate($query->perPage, ['*'], 'page', $query->page); + + return [ + 'tickets' => $tickets, + 'open_count' => (int) ($counts->open_count ?? 0), + 'closed_count' => (int) ($counts->closed_count ?? 0), + ]; + } + + /** + * @return array{root: Ticket, title: string, messages: mixed}|null + */ + public function thread(TicketThreadQuery $query, TicketViewer $viewer): ?array + { + $rootQuery = Ticket::where('id', $query->ticketId)->where('rootid', 0); + if (!$viewer->isAdmin) { + $rootQuery->where('userid', $viewer->actorId); + } + $root = $rootQuery->first(); + if ($root === null) { + return null; + } + + $messages = Ticket::where(static function ($builder) use ($query): void { + $builder->where('id', $query->ticketId) + ->orWhere('rootid', $query->ticketId); + })->orderByDesc('datetime')->orderByDesc('id') + ->paginate($query->perPage, ['*'], 'page', $query->page); + $models = $messages->getCollection(); + $authorIds = $models->pluck('userid')->map(static fn ($id): int => (int) $id) + ->unique()->values()->all(); + $authors = $authorIds === [] + ? collect() + : User::whereIn('id', $authorIds)->get(['id', 'user_name', 'is_admin'])->keyBy('id'); + + $attachmentsByMessage = collect(); + if (!$viewer->isAdmin || $viewer->isSuperAdmin) { + $messageIds = $models->pluck('id')->map(static fn ($id): int => (int) $id)->all(); + if ($messageIds !== []) { + $attachmentsByMessage = TicketAttachment::where('ticket_id', (int) $root->id) + ->whereIn('message_id', $messageIds)->orderBy('id')->get() + ->groupBy('message_id'); + } + } + + $projected = $models->map(function (Ticket $message) use ( + $authors, + $attachmentsByMessage, + $viewer + ): object { + $author = $authors->get((int) $message->userid); + $authorIsAdmin = $author !== null && (int) $author->is_admin === 1; + $content = (string) $message->content; + if ($viewer->isAdmin && !$viewer->isSuperAdmin) { + $content = AdminDataMasker::sensitiveText($content); + } + + $attachments = ($attachmentsByMessage->get((int) $message->id) ?? collect()) + ->map(static function (TicketAttachment $attachment): object { + return (object) [ + 'id' => (int) $attachment->id, + 'name' => (string) $attachment->original_name, + 'mime' => (string) $attachment->mime_type, + 'bytes' => (int) $attachment->bytes, + 'bytes_display' => self::bytes((int) $attachment->bytes), + ]; + })->values()->all(); + + return (object) [ + 'id' => (int) $message->id, + 'content' => $content, + 'datetime' => date('Y-m-d H:i:s', (int) $message->datetime), + 'author_id' => (int) $message->userid, + 'author_is_admin' => $authorIsAdmin, + 'viewer_is_author' => (int) $message->userid === $viewer->actorId, + 'author_name' => $this->authorName($author, $authorIsAdmin, $viewer), + 'attachments' => $attachments, + 'has_attachments' => $attachments !== [], + ]; + }); + $messages->setCollection($projected); + + $title = (string) $root->title; + if ($viewer->isAdmin && !$viewer->isSuperAdmin) { + $title = AdminDataMasker::sensitiveText($title); + } + + return ['root' => $root, 'title' => $title, 'messages' => $messages]; + } + + private function authorName($author, bool $authorIsAdmin, TicketViewer $viewer): string + { + if ($author === null) { + return '用户已删除'; + } + if ((int) $author->id === $viewer->actorId) { + return '我'; + } + if ($authorIsAdmin) { + return '管理员'; + } + $name = (string) $author->user_name; + return $viewer->isAdmin ? AdminDataMasker::account($name) : $name; + } + + private static function bytes(int $bytes): string + { + if ($bytes < 1024) { + return $bytes . ' B'; + } + if ($bytes < 1024 * 1024) { + return number_format($bytes / 1024, 1) . ' KiB'; + } + return number_format($bytes / (1024 * 1024), 1) . ' MiB'; + } +} diff --git a/web/app/Services/Ticket/TicketThreadQuery.php b/web/app/Services/Ticket/TicketThreadQuery.php new file mode 100644 index 00000000..09a09756 --- /dev/null +++ b/web/app/Services/Ticket/TicketThreadQuery.php @@ -0,0 +1,17 @@ +ticketId < 1 || $this->page < 1 + || $this->perPage < 1 || $this->perPage > 100) { + throw new \InvalidArgumentException('工单读取参数无效'); + } + } +} diff --git a/web/app/Services/Ticket/TicketViewer.php b/web/app/Services/Ticket/TicketViewer.php new file mode 100644 index 00000000..f3dc06e2 --- /dev/null +++ b/web/app/Services/Ticket/TicketViewer.php @@ -0,0 +1,23 @@ + (int) $attachment->id, - 'name' => (string) $attachment->original_name, - 'mime' => (string) $attachment->mime_type, - 'bytes' => (int) $attachment->bytes, - 'url' => $prefix . (int) $attachment->id, - ]; - } - private static function directory(): string { $directory = BASE_PATH . '/storage/ticket-attachments'; diff --git a/web/resources/views/venix/admin/ticket/view.tpl b/web/resources/views/venix/admin/ticket/view.tpl index b2f9b692..e9141164 100644 --- a/web/resources/views/venix/admin/ticket/view.tpl +++ b/web/resources/views/venix/admin/ticket/view.tpl @@ -36,8 +36,8 @@

CONVERSATION

沟通记录
{$ticketset->total()} 条消息
{foreach $ticketset as $ticket} - {assign var=ticketIsAdmin value=$ticket->display_author_is_admin} -
{$ticket->display_author_name|escape:'html'}{if $ticketIsAdmin}管理员{else}用户{/if}
{$ticket->display_content|escape:'html'|nl2br}
{if $ticket->attachments|@count > 0}
{foreach $ticket->attachments as $attachment}{$attachment->original_name|escape:'html'}{$attachment->original_name|escape:'html'}{/foreach}
{/if}
+ {assign var=ticketIsAdmin value=$ticket->author_is_admin} +
{$ticket->author_name|escape:'html'}{if $ticketIsAdmin}管理员{else}用户{/if}
{$ticket->content|escape:'html'|nl2br}
{if $ticket->attachments|@count > 0}
{foreach $ticket->attachments as $attachment}{$attachment->name|escape:'html'}{$attachment->name|escape:'html'}{/foreach}
{/if}
{foreachelse}
暂无对话内容
{/foreach}
{$ticketset->render()}
diff --git a/web/resources/views/venix/user/ticket_view.tpl b/web/resources/views/venix/user/ticket_view.tpl index 1cc3effd..90a5026a 100755 --- a/web/resources/views/venix/user/ticket_view.tpl +++ b/web/resources/views/venix/user/ticket_view.tpl @@ -2,7 +2,7 @@

Ticket #{$id}

-

{if isset($ticket_main)}{$ticket_main->title|escape:"html"}{else}工单详情{/if}

+

{$ticket_display_title|default:'工单详情'|escape:"html"}

返回工单 @@ -54,14 +54,14 @@
{foreach $ticketset as $ticket} -
+
- {$ticket->authorName()|escape:"html"} - {$ticket->datetime()} + {$ticket->author_name|escape:"html"} + {$ticket->datetime|escape:"html"}

{$ticket->content|escape:"html"|nl2br}

{if isset($ticket->attachments) && $ticket->attachments} @@ -69,8 +69,8 @@ {foreach $ticket->attachments as $attachment} - {$attachment->original_name|default:'附件'|escape:'html'} - {if $attachment->bytes|default:0}{$attachment->bytes} B{/if} + {$attachment->name|default:'附件'|escape:'html'} + {if $attachment->bytes|default:0}{$attachment->bytes_display|escape:'html'}{/if} {/foreach}
diff --git a/web/tests/AdminTicketPrivacyContractTest.php b/web/tests/AdminTicketPrivacyContractTest.php index 34ed610e..db69106d 100644 --- a/web/tests/AdminTicketPrivacyContractTest.php +++ b/web/tests/AdminTicketPrivacyContractTest.php @@ -3,6 +3,7 @@ $root = dirname(__DIR__); $routes = file_get_contents($root . '/config/routes.php'); $controller = file_get_contents($root . '/app/Controllers/Admin/TicketController.php'); +$readModel = file_get_contents($root . '/app/Services/Ticket/TicketReadModel.php'); $template = file_get_contents($root . '/resources/views/venix/admin/ticket/view.tpl'); $assert = static function ($condition, string $message): void { @@ -19,13 +20,13 @@ $assert( 'Administrator ticket attachments must require the SuperAdmin middleware.' ); $assert( - str_contains($controller, 'AdminDataMasker::sensitiveText((string) $ticketMain->title)') - && str_contains($controller, "->assign('ticket_display_title'"), + str_contains($readModel, 'AdminDataMasker::sensitiveText($title)') + && str_contains($controller, "->assign('ticket_display_title', \$thread['title'])"), 'The administrator ticket title must use a dedicated masked display value.' ); $assert( str_contains($controller, 'AdminPermission::isSuperAdmin()') - && str_contains($controller, 'if ($canViewAttachments)'), + && str_contains($readModel, 'if (!$viewer->isAdmin || $viewer->isSuperAdmin)'), 'Attachment metadata must only be loaded for super administrators.' ); $assert( diff --git a/web/tests/AdminTicketQueueContractTest.php b/web/tests/AdminTicketQueueContractTest.php index da5e61e9..3f2a823f 100644 --- a/web/tests/AdminTicketQueueContractTest.php +++ b/web/tests/AdminTicketQueueContractTest.php @@ -4,6 +4,7 @@ $root = dirname(__DIR__); $template = file_get_contents($root . '/resources/views/venix/admin/ticket/index.tpl'); $controller = file_get_contents($root . '/app/Controllers/Admin/TicketController.php'); $userController = file_get_contents($root . '/app/Controllers/UserController.php'); +$readModel = file_get_contents($root . '/app/Services/Ticket/TicketReadModel.php'); $schema = file_get_contents($root . '/sql/ss.sql'); $assert = static function ($condition, string $message): void { @@ -35,8 +36,9 @@ $assert( 'The ticket API must expose recent activity and complete status totals.' ); $assert( - str_contains($userController, 'last_activity_at') - && str_contains($userController, 'orderByDesc'), + str_contains($userController, 'TicketReadModel') + && str_contains($readModel, 'last_activity_at') + && str_contains($readModel, 'orderByDesc'), 'The user ticket queue must use the same recent-activity ordering contract.' ); $assert( diff --git a/web/tests/TicketReadModelTest.php b/web/tests/TicketReadModelTest.php new file mode 100644 index 00000000..e6c17b91 --- /dev/null +++ b/web/tests/TicketReadModelTest.php @@ -0,0 +1,107 @@ +addConnection(['driver' => 'sqlite', 'database' => ':memory:'], 'default'); +$capsule->setAsGlobal(); +$capsule->bootEloquent(); +$schema = $capsule->getConnection('default')->getSchemaBuilder(); +$schema->create('user', static function (Blueprint $table): void { + $table->increments('id'); + $table->string('user_name'); + $table->boolean('is_admin')->default(false); +}); +$schema->create('ticket', static function (Blueprint $table): void { + $table->increments('id'); + $table->text('title'); + $table->text('content'); + $table->integer('rootid')->default(0); + $table->integer('userid'); + $table->integer('datetime'); + $table->integer('status')->default(1); + $table->string('ticket_type')->default('technical'); + $table->string('priority')->default('medium'); + $table->integer('instance_id')->nullable(); +}); +$schema->create('ticket_attachments', static function (Blueprint $table): void { + $table->increments('id'); + $table->integer('ticket_id'); + $table->integer('message_id'); + $table->integer('user_id'); + $table->string('storage_key'); + $table->string('original_name'); + $table->string('mime_type'); + $table->integer('bytes'); + $table->string('sha256'); + $table->integer('created_at'); +}); + +Capsule::table('user')->insert([ + ['id' => 7, 'user_name' => 'customer', 'is_admin' => 0], + ['id' => 9, 'user_name' => 'operator', 'is_admin' => 1], +]); +$messages = [[ + 'id' => 1, 'title' => 'Cannot connect', 'content' => 'password=secret', + 'rootid' => 0, 'userid' => 7, 'datetime' => 100, 'status' => 1, + 'ticket_type' => 'technical', 'priority' => 'high', 'instance_id' => null, +]]; +for ($id = 2; $id <= 12; $id += 1) { + $messages[] = [ + 'id' => $id, 'title' => 'Cannot connect', 'content' => 'Message ' . $id, + 'rootid' => 1, 'userid' => $id % 2 === 0 ? 9 : 7, + 'datetime' => 100 + $id, 'status' => 1, + 'ticket_type' => 'technical', 'priority' => 'high', 'instance_id' => null, + ]; +} +Capsule::table('ticket')->insert($messages); +Capsule::table('ticket_attachments')->insert([ + 'ticket_id' => 1, 'message_id' => 2, 'user_id' => 9, + 'storage_key' => 'a.png', 'original_name' => 'proof.png', + 'mime_type' => 'image/png', 'bytes' => 1536, + 'sha256' => str_repeat('a', 64), 'created_at' => 102, +]); + +$queryCount = 0; +$capsule->getConnection('default')->listen(static function () use (&$queryCount): void { + $queryCount += 1; +}); +$model = new TicketReadModel(); +$thread = $model->thread( + new TicketThreadQuery(1, 1, 20), + TicketViewer::user(7) +); + +$assert(is_array($thread), 'The owner could not read the ticket thread.'); +$assert($thread['messages']->total() === 12, 'The thread did not return every message.'); +$assert($queryCount <= 5, 'Thread projection query count grows past the fixed read budget.'); +$items = $thread['messages']->items(); +$assert($items[0]->id === 12 && $items[0]->author_name === '管理员', + 'The latest administrator reply was not projected first.'); +$messageTwo = null; +foreach ($items as $item) { + if ($item->id === 2) { + $messageTwo = $item; + break; + } +} +$assert($messageTwo !== null && count($messageTwo->attachments) === 1, + 'The owner cannot see an attachment in their own thread.'); +$assert($messageTwo->attachments[0]->bytes_display === '1.5 KiB', + 'Attachment size is not projected in a human-readable form.'); +$assert($model->thread(new TicketThreadQuery(1), TicketViewer::user(8)) === null, + 'A foreign user can read another user\'s thread.'); + +echo "Ticket read model checks passed.\n";