refactor(ticket): centralize thread read projections
parent
cec49942ed
commit
281c36e990
@ -0,0 +1,15 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Ticket;
|
||||
|
||||
final readonly class TicketQueueQuery
|
||||
{
|
||||
public function __construct(
|
||||
public int $page = 1,
|
||||
public int $perPage = 15
|
||||
) {
|
||||
if ($this->page < 1 || $this->perPage < 1 || $this->perPage > 100) {
|
||||
throw new \InvalidArgumentException('工单分页参数无效');
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,153 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Ticket;
|
||||
|
||||
use App\Models\Ticket;
|
||||
use App\Models\TicketAttachment;
|
||||
use App\Models\User;
|
||||
use App\Services\AdminDataMasker;
|
||||
|
||||
/**
|
||||
* Builds ticket queues and threads in a fixed number of queries.
|
||||
*
|
||||
* Controllers pass the viewer once. Ownership, privacy, authors and private
|
||||
* attachment visibility stay behind this interface instead of being rebuilt
|
||||
* by each HTTP adapter and template.
|
||||
*/
|
||||
final class TicketReadModel
|
||||
{
|
||||
/**
|
||||
* @return array{tickets: mixed, open_count: int, closed_count: int}
|
||||
*/
|
||||
public function queue(TicketQueueQuery $query, TicketViewer $viewer): array
|
||||
{
|
||||
$roots = Ticket::where('rootid', 0);
|
||||
if (!$viewer->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';
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,17 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Ticket;
|
||||
|
||||
final readonly class TicketThreadQuery
|
||||
{
|
||||
public function __construct(
|
||||
public int $ticketId,
|
||||
public int $page = 1,
|
||||
public int $perPage = 8
|
||||
) {
|
||||
if ($this->ticketId < 1 || $this->page < 1
|
||||
|| $this->perPage < 1 || $this->perPage > 100) {
|
||||
throw new \InvalidArgumentException('工单读取参数无效');
|
||||
}
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,23 @@
|
||||
<?php
|
||||
|
||||
namespace App\Services\Ticket;
|
||||
|
||||
final readonly class TicketViewer
|
||||
{
|
||||
private function __construct(
|
||||
public int $actorId,
|
||||
public bool $isAdmin,
|
||||
public bool $isSuperAdmin
|
||||
) {
|
||||
}
|
||||
|
||||
public static function user(int $actorId): self
|
||||
{
|
||||
return new self($actorId, false, false);
|
||||
}
|
||||
|
||||
public static function administrator(int $actorId, bool $isSuperAdmin): self
|
||||
{
|
||||
return new self($actorId, true, $isSuperAdmin);
|
||||
}
|
||||
}
|
||||
@ -0,0 +1,107 @@
|
||||
<?php
|
||||
|
||||
require dirname(__DIR__) . '/vendor/autoload.php';
|
||||
|
||||
use App\Services\Ticket\TicketReadModel;
|
||||
use App\Services\Ticket\TicketThreadQuery;
|
||||
use App\Services\Ticket\TicketViewer;
|
||||
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();
|
||||
$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";
|
||||
Loading…
Reference in New Issue