diff --git a/web/app/Controllers/Admin/TicketController.php b/web/app/Controllers/Admin/TicketController.php index 36453f51..81db6aa3 100644 --- a/web/app/Controllers/Admin/TicketController.php +++ b/web/app/Controllers/Admin/TicketController.php @@ -19,6 +19,7 @@ use App\Services\Ticket\TicketIdempotencyConflict; use App\Services\Ticket\TicketReadModel; use App\Services\Ticket\TicketThreadQuery; use App\Services\Ticket\TicketViewer; +use App\Services\Ticket\TicketReadCommand; use App\Utils\SafeDatatables as Datatables; use App\Utils\DatatablesHelper; @@ -45,7 +46,8 @@ class TicketController extends AdminController ->assign('telegram_bound', $telegram['binding']['bound']) ->assign('telegram_admin_id', $telegram['binding']['admin_id']); } - return $view->display('admin/ticket/index.tpl'); + return $view->assign('ticket_can_search_user', AdminPermission::isSuperAdmin()) + ->display('admin/ticket/index.tpl'); } private function telegramViewState(): array @@ -181,24 +183,40 @@ class TicketController extends AdminController return $this->streamTicketAttachment($response, $attachment); } + public function markRead($request, $response, $args) + { + if (!AdminCsrf::verify($request)) { + return $this->echoJson($response, ['ret' => 0, 'msg' => '请求已过期,请刷新页面后重试']); + } + $marked = (new TicketReadModel())->markRead( + new TicketReadCommand((int) ($args['id'] ?? 0)), + TicketViewer::administrator( + (int) Auth::getUser()->id, + AdminPermission::isSuperAdmin() + ) + ); + if (!$marked) { + return $response->withStatus(404); + } + return $this->echoJson($response, ['ret' => 1]); + } + public function ajax($request, $response, $args) { $datatables = new Datatables(new DatatablesHelper()); - $connection = (new Ticket())->getConnection(); - $schema = $connection->getSchemaBuilder(); - $ticketType = $this->ticketColumnExpression($schema, 'ticket_type', "'technical'"); - $priority = $this->ticketColumnExpression($schema, 'priority', "'medium'"); - $instanceId = $this->ticketColumnExpression($schema, 'instance_id', 'NULL'); + $adminId = (int) Auth::getUser()->id; $datatables->query('SELECT ticket.id AS op,ticket.id,' - . 'CASE WHEN ticket_activity.last_reply_at IS NULL ' - . 'OR ticket_activity.last_reply_at < ticket.datetime ' - . 'THEN ticket.datetime ELSE ticket_activity.last_reply_at END AS datetime,' + . 'ticket.last_activity_at AS datetime,' . 'ticket.title,ticket.userid,user.user_name,' - . $ticketType . ' AS ticket_type,' . $priority . ' AS priority,' . $instanceId - . ' AS instance_id,ticket.status FROM ticket ' + . 'ticket.ticket_type,ticket.priority,ticket.instance_id,ticket.status,' + . 'CASE WHEN COALESCE(ticket_reader.last_read_message_id,0) ' + . '< ticket.last_message_id THEN 1 ELSE 0 END AS unread,' + . "CASE WHEN ticket.status=0 THEN 'closed' " + . "WHEN ticket.last_actor_is_admin=1 THEN 'user' ELSE 'admin' END AS waiting_for " + . 'FROM ticket ' . 'INNER JOIN user ON ticket.userid = user.id ' - . 'LEFT JOIN (SELECT rootid, MAX(datetime) AS last_reply_at FROM ticket ' - . 'WHERE rootid <> 0 GROUP BY rootid) AS ticket_activity ON ticket_activity.rootid = ticket.id ' + . 'LEFT JOIN ticket_read_states AS ticket_reader ' + . 'ON ticket_reader.ticket_id=ticket.id AND ticket_reader.reader_id=' . $adminId . ' ' . 'WHERE ticket.rootid = 0'); $datatables->edit('op', function ($data) { @@ -221,6 +239,14 @@ class TicketController extends AdminController return $data['status'] == 1 ? '开启' : '关闭'; }); + $datatables->edit('waiting_for', function ($data) { + return match ((string) $data['waiting_for']) { + 'admin' => '等待管理员', + 'user' => '等待用户', + default => '已关闭', + }; + }); + $statusTotals = Ticket::where('rootid', 0) ->selectRaw('COUNT(*) AS total') ->selectRaw('SUM(CASE WHEN status = 1 THEN 1 ELSE 0 END) AS open_count') @@ -239,12 +265,4 @@ class TicketController extends AdminController return $response->withHeader('Content-Type', 'application/json; charset=utf-8'); } - private function ticketColumnExpression($schema, string $column, string $fallback): string - { - try { - return $schema->hasColumn('ticket', $column) ? 'ticket.' . $column : $fallback; - } catch (\Throwable $exception) { - return $fallback; - } - } } diff --git a/web/app/Controllers/UserController.php b/web/app/Controllers/UserController.php index d34ed2b1..734c4c97 100644 --- a/web/app/Controllers/UserController.php +++ b/web/app/Controllers/UserController.php @@ -40,6 +40,7 @@ use App\Services\Ticket\TicketQueueQuery; use App\Services\Ticket\TicketReadModel; use App\Services\Ticket\TicketThreadQuery; use App\Services\Ticket\TicketViewer; +use App\Services\Ticket\TicketReadCommand; use App\Services\UserDrawerService; /** @@ -767,6 +768,25 @@ class UserController extends BaseController return $this->streamTicketAttachment($response, $attachment); } + public function ticket_mark_read($request, $response, $args) + { + if (!AdminCsrf::verify($request)) { + return $this->echoJson($response, ['ret' => 0, 'msg' => '请求已过期,请刷新页面后重试']); + } + try { + $marked = (new TicketReadModel())->markRead( + new TicketReadCommand((int) ($args['id'] ?? 0)), + TicketViewer::user((int) $this->user->id) + ); + } catch (\Throwable $exception) { + $marked = false; + } + if (!$marked) { + return $response->withStatus(404); + } + return $this->echoJson($response, ['ret' => 1]); + } + private function ticketInstances(): array { try { diff --git a/web/app/Services/Ticket/TicketReadCommand.php b/web/app/Services/Ticket/TicketReadCommand.php new file mode 100644 index 00000000..154595de --- /dev/null +++ b/web/app/Services/Ticket/TicketReadCommand.php @@ -0,0 +1,13 @@ +ticketId < 1) { + throw new \InvalidArgumentException('工单编号无效'); + } + } +} diff --git a/web/app/Services/Ticket/TicketReadModel.php b/web/app/Services/Ticket/TicketReadModel.php index d2d2561c..0771717c 100644 --- a/web/app/Services/Ticket/TicketReadModel.php +++ b/web/app/Services/Ticket/TicketReadModel.php @@ -21,9 +21,9 @@ final class TicketReadModel */ public function queue(TicketQueueQuery $query, TicketViewer $viewer): array { - $roots = Ticket::where('rootid', 0); + $roots = Ticket::where('ticket.rootid', 0); if (!$viewer->isAdmin) { - $roots->where('userid', $viewer->actorId); + $roots->where('ticket.userid', $viewer->actorId); } $counts = (clone $roots) @@ -31,10 +31,16 @@ final class TicketReadModel ->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') + ->leftJoin('ticket_read_states AS ticket_reader', function ($join) use ($viewer): void { + $join->on('ticket_reader.ticket_id', '=', 'ticket.id') + ->where('ticket_reader.reader_id', '=', $viewer->actorId); + }) + ->select('ticket.*') + ->selectRaw('CASE WHEN COALESCE(ticket_reader.last_read_message_id, 0) ' + . '< ticket.last_message_id THEN 1 ELSE 0 END AS is_unread') + ->selectRaw("CASE WHEN ticket.status = 0 THEN 'closed' " + . "WHEN ticket.last_actor_is_admin = 1 THEN 'user' ELSE 'admin' END AS waiting_for") + ->orderByDesc('ticket.last_activity_at')->orderByDesc('ticket.id') ->paginate($query->perPage, ['*'], 'page', $query->page); return [ @@ -125,6 +131,24 @@ final class TicketReadModel return ['root' => $root, 'title' => $title, 'messages' => $messages]; } + public function markRead(TicketReadCommand $command, TicketViewer $viewer): bool + { + $query = Ticket::where('id', $command->ticketId)->where('rootid', 0); + if (!$viewer->isAdmin) { + $query->where('userid', $viewer->actorId); + } + $root = $query->first(); + if ($root === null) { + return false; + } + $lastMessageId = max((int) $root->id, (int) $root->last_message_id); + (new Ticket())->getConnection()->table('ticket_read_states')->updateOrInsert( + ['ticket_id' => (int) $root->id, 'reader_id' => $viewer->actorId], + ['last_read_message_id' => $lastMessageId, 'read_at' => time()] + ); + return true; + } + private function authorName($author, bool $authorIsAdmin, TicketViewer $viewer): string { if ($author === null) { diff --git a/web/app/Services/Ticket/TicketThreadService.php b/web/app/Services/Ticket/TicketThreadService.php index 64ca5bc5..4aebf5ca 100644 --- a/web/app/Services/Ticket/TicketThreadService.php +++ b/web/app/Services/Ticket/TicketThreadService.php @@ -76,9 +76,17 @@ final class TicketThreadService $ticket->ticket_type = $type; $ticket->priority = $priority; $ticket->instance_id = $instanceId; + $ticket->last_activity_at = (int) $ticket->datetime; + $ticket->last_message_id = 0; + $ticket->last_actor_id = $command->actorId; + $ticket->last_actor_is_admin = 0; if (!$ticket->save()) { throw new \RuntimeException('工单保存失败'); } + $ticket->last_message_id = (int) $ticket->id; + if (!$ticket->save()) { + throw new \RuntimeException('工单活动投影保存失败'); + } $attachments = TicketAttachmentService::store( $command->request, (int) $ticket->id, @@ -86,6 +94,7 @@ final class TicketThreadService $command->actorId, $createdPaths ); + $this->advanceReadState((int) $ticket->id, $command->actorId, (int) $ticket->id); $this->completeIntent($intent, (int) $ticket->id, (int) $ticket->id); return new TicketWriteResult($ticket, $ticket, '新工单', $attachments); }, 1); @@ -160,10 +169,17 @@ final class TicketThreadService $reply->priority = (string) $root->priority; $reply->instance_id = $root->instance_id; - $root->status = $command->status; - if (!$root->save() || !$reply->save()) { + if (!$reply->save()) { throw new \RuntimeException('工单回复保存失败'); } + $root->status = $command->status; + $root->last_activity_at = (int) $reply->datetime; + $root->last_message_id = (int) $reply->id; + $root->last_actor_id = $command->actorId; + $root->last_actor_is_admin = $command->actorIsAdmin ? 1 : 0; + if (!$root->save()) { + throw new \RuntimeException('工单活动投影保存失败'); + } $attachments = TicketAttachmentService::store( $command->request, (int) $root->id, @@ -171,6 +187,11 @@ final class TicketThreadService $command->actorId, $createdPaths ); + $this->advanceReadState( + (int) $root->id, + $command->actorId, + (int) $reply->id + ); $this->completeIntent($intent, (int) $root->id, (int) $reply->id); return new TicketWriteResult($root, $reply, $event, $attachments); }, 1); @@ -256,6 +277,14 @@ final class TicketThreadService } } + private function advanceReadState(int $ticketId, int $readerId, int $messageId): void + { + (new Ticket())->getConnection()->table('ticket_read_states')->updateOrInsert( + ['ticket_id' => $ticketId, 'reader_id' => $readerId], + ['last_read_message_id' => $messageId, 'read_at' => time()] + ); + } + private function replayResult(TicketWriteRequest $intent, string $event): TicketWriteResult { $root = Ticket::where('id', (int) $intent->ticket_id)->where('rootid', 0)->first(); diff --git a/web/config/routes.php b/web/config/routes.php index 27ecf8ee..5a35447a 100644 --- a/web/config/routes.php +++ b/web/config/routes.php @@ -111,6 +111,7 @@ $app->group('/user', function () { $this->post('/ticket', 'App\Controllers\UserController:ticket_add'); $this->get('/ticket/{id}/view', 'App\Controllers\UserController:ticket_view'); $this->get('/ticket/{id}/attachment/{attachment_id:[0-9]+}', 'App\Controllers\UserController:ticket_attachment'); + $this->post('/ticket/{id}/read', 'App\Controllers\UserController:ticket_mark_read'); // Multipart replies use POST so PHP reliably exposes uploaded files in // $_FILES; the legacy PUT endpoint remains available for text clients. $this->post('/ticket/{id}/reply', 'App\Controllers\UserController:ticket_update'); @@ -205,6 +206,7 @@ $app->group('/admin', function () { $this->get('/ticket', 'App\Controllers\Admin\TicketController:index'); $this->get('/ticket/{id}/view', 'App\Controllers\Admin\TicketController:show'); $this->get('/ticket/{id}/attachment/{attachment_id:[0-9]+}', 'App\Controllers\Admin\TicketController:attachment')->add(new SuperAdmin()); + $this->post('/ticket/{id}/read', 'App\Controllers\Admin\TicketController:markRead'); // Keep multipart administrator replies on POST for PHP upload parsing; // existing PUT clients continue to use the original endpoint. $this->post('/ticket/{id}/reply', 'App\Controllers\Admin\TicketController:update')->add(new SuperAdmin()); diff --git a/web/public/theme/venix/js/ticket-page.js b/web/public/theme/venix/js/ticket-page.js index 741ae941..84858552 100644 --- a/web/public/theme/venix/js/ticket-page.js +++ b/web/public/theme/venix/js/ticket-page.js @@ -351,8 +351,24 @@ }); } + function markThreadRead() { + var form = qs("#supportTicketReply"); + var ticketId; + if (!form) return; + ticketId = form.getAttribute("data-ticket-id"); + if (!ticketId) return; + fetch("/user/ticket/" + encodeURIComponent(ticketId) + "/read", { + method: "POST", + credentials: "same-origin", + headers: Object.assign({ "X-Requested-With": "XMLHttpRequest" }, csrfHeaders()) + }).catch(function () { + /* Reading the thread remains useful even when acknowledgement is delayed. */ + }); + } + document.addEventListener("DOMContentLoaded", function () { bindCreate(); bindReply(); + markThreadRead(); }); })(); diff --git a/web/resources/views/venix/admin/ticket/index.tpl b/web/resources/views/venix/admin/ticket/index.tpl index 61a682d3..4273b6b6 100644 --- a/web/resources/views/venix/admin/ticket/index.tpl +++ b/web/resources/views/venix/admin/ticket/index.tpl @@ -65,7 +65,7 @@