You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
virt/web/app/Services/Ticket/TicketThreadService.php

269 lines
10 KiB
PHP

<?php
namespace App\Services\Ticket;
use App\Models\CloudInstance;
use App\Models\Ticket;
use App\Models\TicketAttachment;
use App\Models\TicketWriteRequest;
use App\Services\TicketAttachmentService;
use voku\helper\AntiXSS;
/**
* Owns the complete ticket thread mutation contract.
*
* The HTTP adapters only translate requests and responses. Validation,
* sanitization, ownership, row locking, status transitions, attachment rows
* and rollback cleanup remain atomic behind this interface.
*/
final class TicketThreadService
{
public function open(OpenTicketCommand $command): TicketWriteResult
{
$title = $this->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';
$requestHash = $this->requestHash('open', [
'title' => $title,
'content' => $content,
'type' => $type,
'priority' => $priority,
'instance_id' => $command->instanceId,
], $command->request, $command->requestKey);
$connection = (new Ticket())->getConnection();
$createdPaths = [];
try {
return $connection->transaction(function () use (
$command,
$title,
$content,
$type,
$priority,
$requestHash,
&$createdPaths
): TicketWriteResult {
[$intent, $replay] = $this->claimIntent(
$command->actorId,
$command->requestKey,
$requestHash,
'open',
'新工单'
);
if ($replay !== null) {
return $replay;
}
$instanceId = $this->ownedInstanceId($command->actorId, $command->instanceId);
$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
);
$this->completeIntent($intent, (int) $ticket->id, (int) $ticket->id);
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, '请填写回复内容');
$event = $command->actorIsAdmin ? '管理员回复工单' : '用户回复工单';
$requestHash = $this->requestHash('reply', [
'ticket_id' => $command->ticketId,
'content' => $content,
'status' => $command->status,
], $command->request, $command->requestKey);
$connection = (new Ticket())->getConnection();
$createdPaths = [];
try {
return $connection->transaction(function () use (
$command,
$content,
$event,
$requestHash,
&$createdPaths
): ?TicketWriteResult {
[$intent, $replay] = $this->claimIntent(
$command->actorId,
$command->requestKey,
$requestHash,
'reply',
$event
);
if ($replay !== null) {
return $replay;
}
$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) {
$intent->delete();
return null;
}
$event = $command->status === 1 && (int) $root->status !== 1
? '工单重新开启'
: $event;
$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
);
$this->completeIntent($intent, (int) $root->id, (int) $reply->id);
return new TicketWriteResult($root, $reply, $event, $attachments);
}, 1);
} catch (\Throwable $exception) {
TicketAttachmentService::discardPaths($createdPaths);
throw $exception;
}
}
private function requestHash(
string $operation,
array $payload,
mixed $request,
string $requestKey
): string {
if (preg_match('/^[A-Za-z0-9_.-]{16,128}$/D', $requestKey) !== 1) {
throw new \InvalidArgumentException('请求幂等标识无效');
}
$encoded = json_encode([
'operation' => $operation,
'payload' => $payload,
'attachments' => TicketAttachmentService::fingerprints($request),
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
if (!is_string($encoded)) {
throw new \RuntimeException('工单请求摘要生成失败');
}
return hash('sha256', $encoded);
}
/**
* @return array{TicketWriteRequest, TicketWriteResult|null}
*/
private function claimIntent(
int $actorId,
string $requestKey,
string $requestHash,
string $operation,
string $event
): array {
$connection = (new TicketWriteRequest())->getConnection();
$inserted = $connection->table('ticket_write_requests')->insertOrIgnore([
'actor_user_id' => $actorId,
'request_key' => $requestKey,
'request_hash' => $requestHash,
'operation' => $operation,
'ticket_id' => null,
'message_id' => null,
'created_at' => time(),
]);
$intent = TicketWriteRequest::where('actor_user_id', $actorId)
->where('request_key', $requestKey)->lockForUpdate()->first();
if ($intent === null) {
throw new \RuntimeException('工单写入意图保存失败');
}
if ((string) $intent->request_hash !== $requestHash
|| (string) $intent->operation !== $operation) {
throw new TicketIdempotencyConflict();
}
if ((int) $inserted === 0) {
if ($intent->ticket_id === null || $intent->message_id === null) {
throw new \RuntimeException('工单写入意图结果不完整');
}
return [$intent, $this->replayResult($intent, $event)];
}
return [$intent, null];
}
private function completeIntent(TicketWriteRequest $intent, int $ticketId, int $messageId): void
{
$intent->ticket_id = $ticketId;
$intent->message_id = $messageId;
if (!$intent->save()) {
throw new \RuntimeException('工单写入结果保存失败');
}
}
private function replayResult(TicketWriteRequest $intent, string $event): TicketWriteResult
{
$root = Ticket::where('id', (int) $intent->ticket_id)->where('rootid', 0)->first();
$message = Ticket::where('id', (int) $intent->message_id)->first();
if ($root === null || $message === null) {
throw new \RuntimeException('工单写入结果已不存在');
}
$attachments = TicketAttachment::where('ticket_id', (int) $root->id)
->where('message_id', (int) $message->id)->orderBy('id')->get()->all();
return new TicketWriteResult($root, $message, $event, $attachments, false);
}
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;
}
}