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'; $fingerprints = TicketAttachmentService::fingerprints($command->request); $attachmentBytes = $this->fingerprintBytes($fingerprints); $requestHash = $this->requestHash('open', [ 'title' => $title, 'content' => $content, 'type' => $type, 'priority' => $priority, 'instance_id' => $command->instanceId, ], $fingerprints, $command->requestKey); $connection = (new Ticket())->getConnection(); $createdPaths = []; try { return $connection->transaction(function () use ( $command, $title, $content, $type, $priority, $requestHash, $attachmentBytes, &$createdPaths ): TicketWriteResult { [$intent, $replay] = $this->claimIntent( $command->actorId, $command->requestKey, $requestHash, 'open', '新工单' ); if ($replay !== null) { return $replay; } (new TicketUsagePolicy())->assertOpen( $command->actorId, $title, $content, $attachmentBytes ); $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; $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, (int) $ticket->id, $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); } 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('工单状态无效'); } if ($command->requiredCurrentStatus !== null && !in_array($command->requiredCurrentStatus, [0, 1], true)) { throw new \InvalidArgumentException('工单当前状态限制无效'); } $content = $this->cleanRequired($command->content, '请填写回复内容'); $event = $command->actorIsAdmin ? '管理员回复工单' : '用户回复工单'; $fingerprints = TicketAttachmentService::fingerprints($command->request); $attachmentBytes = $this->fingerprintBytes($fingerprints); $requestHash = $this->requestHash('reply', [ 'ticket_id' => $command->ticketId, 'content' => $content, 'status' => $command->status, ], $fingerprints, $command->requestKey); $connection = (new Ticket())->getConnection(); $createdPaths = []; try { return $connection->transaction(function () use ( $command, $content, $event, $requestHash, $attachmentBytes, &$createdPaths ): ?TicketWriteResult { [$intent, $replay] = $this->claimIntent( $command->actorId, $command->requestKey, $requestHash, 'reply', $event ); if ($replay !== null) { return $replay; } (new TicketUsagePolicy())->assertReply( $command->actorId, $content, $attachmentBytes, $command->actorIsAdmin ); $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; } if ($command->requiredCurrentStatus !== null && (int) $root->status !== $command->requiredCurrentStatus) { throw new TicketReplyStateConflict(); } $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; 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, (int) $reply->id, $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); } catch (\Throwable $exception) { TicketAttachmentService::discardPaths($createdPaths); throw $exception; } } private function requestHash( string $operation, array $payload, array $fingerprints, 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' => $fingerprints, ], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES); if (!is_string($encoded)) { throw new \RuntimeException('工单请求摘要生成失败'); } return hash('sha256', $encoded); } private function fingerprintBytes(array $fingerprints): int { $bytes = 0; foreach ($fingerprints as $fingerprint) { $bytes += (int) ($fingerprint['bytes'] ?? 0); } return $bytes; } /** * @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 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(); $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; } }