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/TicketReplyService.php

104 lines
3.8 KiB
PHTML

<?php
namespace App\Services;
use App\Models\Ticket;
/**
* Atomically append a message to an existing ticket thread.
*
* A ticket thread has one root row whose status is the source of truth. The
* root row is therefore selected with a row lock inside the same transaction
* that writes the reply and its attachment rows. Filesystem paths created by
* the attachment writer are explicitly discarded if the transaction cannot
* commit; a database rollback alone cannot remove those files.
*/
final class TicketReplyService
{
/**
* @param mixed $request PSR-7 request, including uploaded files
* @param int|null $ownerId Restrict the root to this user for user replies
* @return array{root: Ticket, reply: Ticket, event: string, attachments: array}|null
*/
public static function create(
int $ticketId,
int $actorId,
string $content,
int $status,
$request,
?int $ownerId = null
): ?array {
if (!in_array($status, [0, 1], true)) {
throw new \InvalidArgumentException('工单状态无效');
}
$connection = (new Ticket())->getConnection();
$createdPaths = [];
try {
return $connection->transaction(function () use (
$ticketId,
$actorId,
$content,
$status,
$request,
$ownerId,
&$createdPaths
) {
// This query must be inside the transaction. A lock acquired
// in autocommit mode would be released before the reply save.
$query = Ticket::where('id', $ticketId)->where('rootid', 0);
if ($ownerId !== null) {
$query->where('userid', $ownerId);
}
$root = $query->lockForUpdate()->first();
if ($root === null) {
return null;
}
$event = $status === 1 && (int) $root->status !== 1
? '工单重新开启'
: '用户回复工单';
$reply = new Ticket();
$reply->title = (string) $root->title;
$reply->content = $content;
$reply->rootid = (int) $root->id;
$reply->userid = $actorId;
$reply->datetime = time();
$reply->status = $status;
$reply->ticket_type = (string) $root->ticket_type;
$reply->priority = (string) $root->priority;
$reply->instance_id = $root->instance_id;
$root->status = $status;
if (!$root->save() || !$reply->save()) {
throw new \RuntimeException('工单回复保存失败');
}
// Keep attachment rows in this transaction. The service also
// records every newly-created path for commit-failure cleanup.
$attachments = TicketAttachmentService::store(
$request,
(int) $root->id,
(int) $reply->id,
$actorId,
$createdPaths
);
return [
'root' => $root,
'reply' => $reply,
'event' => $event,
'attachments' => $attachments,
];
}, 1);
} catch (\Throwable $exception) {
// The DB transaction has already rolled back (or failed to
// commit) when control reaches here. Only remove files created by
// this request; never delete pre-existing ticket attachments.
TicketAttachmentService::discardPaths($createdPaths);
throw $exception;
}
}
}