2024-11-30 19:48:01 -05:00
|
|
|
<?php
|
2026-04-13 20:56:10 -04:00
|
|
|
|
2024-11-30 19:48:01 -05:00
|
|
|
header('Content-Type: application/json');
|
|
|
|
|
|
2026-09-11 12:17:15 -04:00
|
|
|
require_once __DIR__ . '/helpers/ErrorHandler.php';
|
|
|
|
|
ErrorHandler::init();
|
2024-12-02 21:21:10 -05:00
|
|
|
|
2026-09-08 21:28:18 -04:00
|
|
|
require_once __DIR__ . '/middleware/RateLimitMiddleware.php';
|
|
|
|
|
RateLimitMiddleware::apply('api');
|
|
|
|
|
|
2026-09-11 11:42:21 -04:00
|
|
|
// Early friendly JSON error if .env is missing, before config.php's own
|
|
|
|
|
// (plain-text die()) handling would otherwise run — this is a JSON API
|
|
|
|
|
// endpoint and must always respond with a JSON body.
|
|
|
|
|
if (!file_exists(__DIR__ . '/.env')) {
|
2024-11-30 19:48:01 -05:00
|
|
|
echo json_encode([
|
|
|
|
|
'success' => false,
|
|
|
|
|
'error' => 'Configuration file not found'
|
|
|
|
|
]);
|
|
|
|
|
exit;
|
|
|
|
|
}
|
|
|
|
|
|
2026-09-11 11:42:21 -04:00
|
|
|
// Load application config so UrlHelper can resolve APP_DOMAIN, and so the
|
|
|
|
|
// DB connection below (via Database::getConnection()) gets the same
|
|
|
|
|
// charset/timezone sync as every other endpoint instead of a hand-rolled
|
|
|
|
|
// second connection.
|
|
|
|
|
require_once __DIR__ . '/config/config.php';
|
|
|
|
|
require_once __DIR__ . '/helpers/Database.php';
|
2024-11-30 19:48:01 -05:00
|
|
|
|
2026-09-11 11:42:21 -04:00
|
|
|
try {
|
|
|
|
|
$conn = Database::getConnection();
|
|
|
|
|
} catch (\Throwable $e) {
|
|
|
|
|
error_log('create_ticket_api: DB connection failed: ' . $e->getMessage());
|
2026-06-30 09:34:57 -04:00
|
|
|
http_response_code(500);
|
2024-11-30 19:48:01 -05:00
|
|
|
echo json_encode([
|
|
|
|
|
'success' => false,
|
2026-06-30 09:34:57 -04:00
|
|
|
'error' => 'Internal server error'
|
2024-11-30 19:48:01 -05:00
|
|
|
]);
|
|
|
|
|
exit;
|
|
|
|
|
}
|
2026-02-10 12:31:49 -05:00
|
|
|
|
2026-01-01 15:40:32 -05:00
|
|
|
// Authenticate via API key
|
|
|
|
|
require_once __DIR__ . '/middleware/ApiKeyAuth.php';
|
|
|
|
|
require_once __DIR__ . '/models/AuditLogModel.php';
|
2026-07-10 16:11:26 -04:00
|
|
|
require_once __DIR__ . '/models/StatsModel.php';
|
2026-09-11 12:37:46 -04:00
|
|
|
require_once __DIR__ . '/models/TicketModel.php';
|
|
|
|
|
require_once __DIR__ . '/models/WorkflowModel.php';
|
2026-01-30 18:51:16 -05:00
|
|
|
require_once __DIR__ . '/helpers/UrlHelper.php';
|
2026-11-11 01:35:48 -05:00
|
|
|
require_once __DIR__ . '/helpers/TicketHash.php';
|
2026-11-25 20:22:06 -05:00
|
|
|
require_once __DIR__ . '/services/AutoTicketService.php';
|
2026-01-01 15:40:32 -05:00
|
|
|
|
|
|
|
|
$apiKeyAuth = new ApiKeyAuth($conn);
|
|
|
|
|
|
|
|
|
|
try {
|
|
|
|
|
$systemUser = $apiKeyAuth->authenticate();
|
|
|
|
|
} catch (Exception $e) {
|
|
|
|
|
// Authentication failed - ApiKeyAuth already sent the response
|
|
|
|
|
exit;
|
|
|
|
|
}
|
|
|
|
|
|
2026-07-15 18:24:50 -04:00
|
|
|
// Ticket creation is a write — a read-only key must be rejected with 403.
|
|
|
|
|
$apiKeyAuth->requireScope('read_write');
|
|
|
|
|
|
2026-01-01 15:40:32 -05:00
|
|
|
$userId = $systemUser['user_id'];
|
|
|
|
|
|
2025-02-27 22:12:28 -05:00
|
|
|
// Parse input regardless of content-type header
|
|
|
|
|
$rawInput = file_get_contents('php://input');
|
|
|
|
|
$data = json_decode($rawInput, true);
|
|
|
|
|
|
2026-04-06 17:07:11 -04:00
|
|
|
// Validate required fields before any processing
|
|
|
|
|
if (!is_array($data) || empty($data['title'])) {
|
|
|
|
|
// Try URL-encoded fallback
|
|
|
|
|
if (empty($data['title'])) {
|
|
|
|
|
parse_str($rawInput, $urlData);
|
|
|
|
|
if (!empty($urlData['title'])) {
|
|
|
|
|
$data = $urlData;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
if (!is_array($data) || empty($data['title'])) {
|
|
|
|
|
http_response_code(400);
|
|
|
|
|
echo json_encode(['success' => false, 'error' => 'title is required']);
|
|
|
|
|
exit;
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-06 17:40:36 -04:00
|
|
|
// Shared ticket data
|
|
|
|
|
$title = (string)($data['title'] ?? '');
|
|
|
|
|
$description = (string)($data['description'] ?? '');
|
|
|
|
|
$status = (string)($data['status'] ?? 'Open');
|
|
|
|
|
$priority = $data['priority'] ?? '4';
|
|
|
|
|
$category = (string)($data['category'] ?? 'General');
|
|
|
|
|
$type = (string)($data['type'] ?? 'Issue');
|
|
|
|
|
|
2026-06-30 12:26:28 -04:00
|
|
|
// Validate externally-supplied status and priority. (category/type are free-form
|
|
|
|
|
// in this schema.) A non-numeric priority would otherwise cast to 0 and escalate
|
|
|
|
|
// the ticket below P1 on the dedup/update path.
|
|
|
|
|
$validStatuses = $GLOBALS['config']['TICKET_STATUSES'] ?? ['Open', 'Pending', 'In Progress', 'Closed'];
|
|
|
|
|
if (!in_array($status, $validStatuses, true)) {
|
|
|
|
|
http_response_code(400);
|
|
|
|
|
echo json_encode(['success' => false, 'error' => 'Invalid status']);
|
|
|
|
|
exit;
|
|
|
|
|
}
|
|
|
|
|
if (!is_numeric($priority) || (int)$priority < 1 || (int)$priority > 5) {
|
|
|
|
|
http_response_code(400);
|
|
|
|
|
echo json_encode(['success' => false, 'error' => 'Invalid priority (must be 1-5)']);
|
|
|
|
|
exit;
|
|
|
|
|
}
|
|
|
|
|
$priority = (int)$priority;
|
|
|
|
|
|
2026-11-25 20:22:06 -05:00
|
|
|
// An explicit dedup_key (#123) decides what "the same problem" is. A
|
|
|
|
|
// malformed one is an error, never a silent fall back to title hashing.
|
|
|
|
|
if (isset($data['dedup_key']) && $data['dedup_key'] !== '' && !TicketHash::isValidKey($data['dedup_key'])) {
|
|
|
|
|
http_response_code(400);
|
|
|
|
|
echo json_encode([
|
|
|
|
|
'success' => false,
|
|
|
|
|
'error' => 'Invalid dedup_key: use 1-128 of A-Z a-z 0-9 _ . : - (e.g. host:compute-storage-01:oom)',
|
|
|
|
|
]);
|
|
|
|
|
exit;
|
|
|
|
|
}
|
|
|
|
|
$dedupKey = TicketHash::key($data);
|
|
|
|
|
|
|
|
|
|
// Which reporter this is (gandalf, hwmonDaemon, thor): the API key's name.
|
|
|
|
|
// Recorded as the ticket's source and used as the author of the comments
|
|
|
|
|
// this endpoint writes.
|
|
|
|
|
$source = (string)($apiKeyAuth->getKeyContext()['key_name'] ?? 'API');
|
|
|
|
|
$commentAuthor = mb_substr($source, 0, 50);
|
|
|
|
|
|
2026-11-11 01:35:48 -05:00
|
|
|
$ticketHash = TicketHash::generate($data);
|
2026-04-06 17:40:36 -04:00
|
|
|
$auditLog = new AuditLogModel($conn);
|
|
|
|
|
|
2026-09-11 21:41:57 -04:00
|
|
|
// Everything from here through either updating/reopening the matched ticket
|
|
|
|
|
// or inserting a brand-new one runs inside one transaction with a row lock
|
|
|
|
|
// on the hash lookup. Without this, two concurrent requests carrying the
|
|
|
|
|
// same dedup hash (e.g. overlapping monitoring runs) could both read the
|
|
|
|
|
// same pre-update snapshot and each independently apply an escalation. FOR
|
|
|
|
|
// UPDATE on this equality lookup against the unique-indexed hash column also
|
|
|
|
|
// takes a lock on the "gap" where no row currently exists, so two concurrent
|
|
|
|
|
// requests for a genuinely new hash are still safe from a duplicate row —
|
|
|
|
|
// but that gap lock is shared, not exclusive, so both can reach the INSERT
|
|
|
|
|
// below and deadlock with each other rather than one blocking cleanly on the
|
|
|
|
|
// other's row. See the retry loop and comment near the INSERT's catch block
|
|
|
|
|
// for how that case is handled.
|
|
|
|
|
// Retried once if the INSERT below deadlocks with another connection's
|
|
|
|
|
// concurrent insert into the same not-yet-existing hash (see comment
|
|
|
|
|
// above the INSERT's catch block) — the retry's own SELECT ... FOR UPDATE
|
|
|
|
|
// will then find the winner's already-committed row and take the
|
|
|
|
|
// update/escalate branch instead of erroring out.
|
|
|
|
|
$maxDedupAttempts = 2;
|
|
|
|
|
for ($dedupAttempt = 1; $dedupAttempt <= $maxDedupAttempts; $dedupAttempt++) {
|
|
|
|
|
$conn->begin_transaction();
|
|
|
|
|
|
2026-11-25 20:22:06 -05:00
|
|
|
// Look up the ticket holding this hash (open OR closed)
|
|
|
|
|
$existing = AutoTicketService::lockByHash($conn, $ticketHash);
|
2026-09-11 21:41:57 -04:00
|
|
|
|
2026-11-25 20:22:06 -05:00
|
|
|
if ($existing && ($existing['status'] !== 'Closed' || $existing['closed_recently'])) {
|
2026-09-11 21:41:57 -04:00
|
|
|
$existingId = $existing['ticket_id'];
|
|
|
|
|
$existingStatus = $existing['status'];
|
|
|
|
|
$existingTitle = $existing['title'];
|
|
|
|
|
$existingPriority = (int)$existing['priority'];
|
|
|
|
|
$newPriority = (int)$priority;
|
|
|
|
|
|
|
|
|
|
if ($existingStatus !== 'Closed') {
|
|
|
|
|
// Ticket is still active — update title, escalate priority, and refresh
|
|
|
|
|
// description with latest sensor data.
|
|
|
|
|
$changes = [];
|
|
|
|
|
$updateSql = "UPDATE tickets SET updated_at = NOW(), updated_by = ?";
|
|
|
|
|
$bindTypes = "i";
|
|
|
|
|
$bindVals = [$userId];
|
|
|
|
|
|
|
|
|
|
if ($title !== $existingTitle) {
|
|
|
|
|
$updateSql .= ", title = ?";
|
|
|
|
|
$bindTypes .= "s";
|
|
|
|
|
$bindVals[] = $title;
|
|
|
|
|
$changes['title'] = ['from' => $existingTitle, 'to' => $title];
|
|
|
|
|
}
|
2026-04-06 18:55:15 -04:00
|
|
|
|
2026-09-11 21:41:57 -04:00
|
|
|
if ($newPriority < $existingPriority) {
|
|
|
|
|
$updateSql .= ", priority = ?";
|
|
|
|
|
$bindTypes .= "i";
|
|
|
|
|
$bindVals[] = $newPriority;
|
|
|
|
|
$changes['priority'] = ['from' => $existingPriority, 'to' => $newPriority];
|
|
|
|
|
}
|
2026-04-06 18:55:15 -04:00
|
|
|
|
2026-09-11 21:41:57 -04:00
|
|
|
// Always refresh the description so the ticket body shows current sensor data
|
|
|
|
|
if (!empty($description)) {
|
|
|
|
|
$updateSql .= ", description = ?";
|
|
|
|
|
$bindTypes .= "s";
|
|
|
|
|
$bindVals[] = $description;
|
|
|
|
|
$changes['description_refreshed'] = true;
|
|
|
|
|
}
|
2026-04-16 08:06:13 -04:00
|
|
|
|
2026-09-11 21:41:57 -04:00
|
|
|
if (!empty($changes)) {
|
|
|
|
|
$updateSql .= " WHERE ticket_id = ?";
|
|
|
|
|
$bindTypes .= "s";
|
|
|
|
|
$bindVals[] = $existingId;
|
|
|
|
|
|
|
|
|
|
$updStmt = $conn->prepare($updateSql);
|
|
|
|
|
$updStmt->bind_param($bindTypes, ...$bindVals);
|
|
|
|
|
$updStmt->execute();
|
|
|
|
|
$updStmt->close();
|
|
|
|
|
|
|
|
|
|
// Only post a comment on priority escalation — title and description updates
|
|
|
|
|
// are silent (title changes like rising counters would spam a comment every run).
|
|
|
|
|
// Keep it short: the full sensor data is refreshed in the ticket description,
|
|
|
|
|
// so the comment just records the bump + a brief reason (no ASCII dump).
|
|
|
|
|
if (isset($changes['priority'])) {
|
|
|
|
|
$pLabels = [1 => 'P1 (Critical)', 2 => 'P2 (High)', 3 => 'P3 (Medium)', 4 => 'P4 (Low)', 5 => 'P5 (Minimal)'];
|
|
|
|
|
$fromP = (int)$changes['priority']['from'];
|
|
|
|
|
$toP = (int)$changes['priority']['to'];
|
|
|
|
|
$fromL = $pLabels[$fromP] ?? "P{$fromP}";
|
|
|
|
|
$toL = $pLabels[$toP] ?? "P{$toP}";
|
2026-11-25 20:22:06 -05:00
|
|
|
$commentText = "**{$source} raised priority {$fromL} → {$toL}.**\n\n"
|
|
|
|
|
. "The latest report described a more severe condition for this issue, "
|
|
|
|
|
. "so it now needs faster attention. Current details are in the ticket description above.";
|
2026-09-11 21:41:57 -04:00
|
|
|
$commentStmt = $conn->prepare(
|
2026-11-25 20:22:06 -05:00
|
|
|
"INSERT INTO ticket_comments (ticket_id, user_id, user_name, comment_text, markdown_enabled) VALUES (?, ?, ?, ?, 1)"
|
2026-09-11 21:41:57 -04:00
|
|
|
);
|
2026-11-25 20:22:06 -05:00
|
|
|
$commentStmt->bind_param("siss", $existingId, $userId, $commentAuthor, $commentText);
|
2026-09-11 21:41:57 -04:00
|
|
|
$commentStmt->execute();
|
|
|
|
|
$commentStmt->close();
|
|
|
|
|
}
|
|
|
|
|
|
2026-09-25 15:34:44 -04:00
|
|
|
// Audit only real title/priority changes. The description is
|
|
|
|
|
// refreshed on every run, and logging that alone wrote a
|
|
|
|
|
// reason-only row every few minutes per open ticket — 50k+ rows
|
|
|
|
|
// on one ticket, which broke its page (tinker_tickets#112).
|
|
|
|
|
$auditedChanges = array_diff_key($changes, ['description_refreshed' => true]);
|
|
|
|
|
if (!empty($auditedChanges)) {
|
|
|
|
|
$auditLog->log($userId, 'update', 'ticket', $existingId, array_merge(
|
|
|
|
|
$auditedChanges,
|
2026-11-25 20:22:06 -05:00
|
|
|
['reason' => "auto-updated by {$source} (condition worsened)"]
|
2026-09-25 15:34:44 -04:00
|
|
|
));
|
|
|
|
|
}
|
2026-09-11 21:41:57 -04:00
|
|
|
|
|
|
|
|
// Only notify on priority escalation — title-only updates (e.g. rising
|
|
|
|
|
// Power_On_Hours counter) should not generate a Matrix ping every hour.
|
|
|
|
|
if (isset($changes['priority'])) {
|
|
|
|
|
require_once __DIR__ . '/helpers/NotificationHelper.php';
|
|
|
|
|
NotificationHelper::sendTicketNotification($existingId, [
|
|
|
|
|
'title' => $title,
|
|
|
|
|
'priority' => $changes['priority']['to'],
|
|
|
|
|
'category' => $category,
|
|
|
|
|
'type' => $type,
|
|
|
|
|
'status' => $existingStatus,
|
|
|
|
|
], 'automated');
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Ticket state (priority/title/description) changed — refresh dashboard stats.
|
|
|
|
|
(new StatsModel($conn))->invalidateCache();
|
2026-04-06 18:55:15 -04:00
|
|
|
}
|
|
|
|
|
|
2026-09-11 21:41:57 -04:00
|
|
|
$conn->commit();
|
|
|
|
|
Database::close();
|
|
|
|
|
echo json_encode([
|
|
|
|
|
'success' => true,
|
|
|
|
|
'ticket_id' => $existingId,
|
|
|
|
|
'message' => empty($changes) ? 'Duplicate — no change' : 'Existing ticket updated',
|
|
|
|
|
'action' => empty($changes) ? 'deduplicated' : 'updated',
|
|
|
|
|
'changes' => $changes,
|
|
|
|
|
]);
|
|
|
|
|
exit;
|
|
|
|
|
}
|
2026-04-06 18:55:15 -04:00
|
|
|
|
2026-11-25 20:22:06 -05:00
|
|
|
// Ticket closed inside the reopen window: reopen it and add a recurrence comment. Route
|
2026-09-11 21:41:57 -04:00
|
|
|
// through the Workflow Designer like every other status-write path in
|
|
|
|
|
// the app, rather than forcing status='Open' via raw SQL regardless of
|
|
|
|
|
// configured transition rules.
|
|
|
|
|
$workflowModel = new WorkflowModel($conn);
|
|
|
|
|
$reopenStatus = 'Open';
|
|
|
|
|
if (!$workflowModel->isTransitionAllowed('Closed', 'Open', false)) {
|
|
|
|
|
// Direct Closed->Open isn't configured — fall back to any transition
|
|
|
|
|
// the Workflow Designer does allow from Closed that this unattended,
|
|
|
|
|
// non-admin automation can actually satisfy (no comment prompt, no
|
|
|
|
|
// admin elevation). If even that doesn't exist, leave the ticket
|
|
|
|
|
// Closed rather than force an unconfigured state.
|
|
|
|
|
$reopenStatus = null;
|
|
|
|
|
foreach ($workflowModel->getAllowedTransitions('Closed') as $transition) {
|
|
|
|
|
if (!$transition['requires_comment'] && !$transition['requires_admin']) {
|
|
|
|
|
$reopenStatus = $transition['to_status'];
|
|
|
|
|
break;
|
|
|
|
|
}
|
2026-04-06 21:43:22 -04:00
|
|
|
}
|
2026-09-11 21:41:57 -04:00
|
|
|
}
|
2026-07-10 16:11:26 -04:00
|
|
|
|
2026-09-11 21:41:57 -04:00
|
|
|
if ($reopenStatus !== null) {
|
|
|
|
|
$ticketModel = new TicketModel($conn);
|
|
|
|
|
$ticketModel->updateTicket([
|
|
|
|
|
'ticket_id' => $existingId,
|
|
|
|
|
'title' => $title,
|
|
|
|
|
'description' => $description,
|
|
|
|
|
'category' => $category,
|
|
|
|
|
'type' => $type,
|
|
|
|
|
'status' => $reopenStatus,
|
|
|
|
|
'priority' => $priority,
|
|
|
|
|
], $userId);
|
|
|
|
|
} else {
|
2026-11-25 20:22:06 -05:00
|
|
|
error_log("create_ticket_api: {$source} recurrence for ticket $existingId: "
|
2026-09-11 21:41:57 -04:00
|
|
|
. "no admin-free, comment-free transition from Closed is configured; leaving ticket Closed");
|
|
|
|
|
}
|
|
|
|
|
|
2026-11-25 20:22:06 -05:00
|
|
|
$commentText = "**Issue recurred, ticket reopened automatically.**\n\n"
|
|
|
|
|
. "{$source} detected this condition again. The ticket description reflects the "
|
|
|
|
|
. "latest report; see this comment's timestamp for when the issue recurred.";
|
2026-09-11 21:41:57 -04:00
|
|
|
if ($reopenStatus === null) {
|
|
|
|
|
$commentText = "**Issue recurred, but the ticket could not be reopened automatically.**\n\n"
|
2026-11-25 20:22:06 -05:00
|
|
|
. "{$source} detected this condition again. No Workflow Designer transition from "
|
2026-09-11 21:41:57 -04:00
|
|
|
. "Closed is configured that this automation can perform unattended (no comment/admin "
|
|
|
|
|
. "requirement); the ticket remains Closed. Please review and reopen manually if appropriate.";
|
|
|
|
|
}
|
|
|
|
|
$commentStmt = $conn->prepare(
|
2026-11-25 20:22:06 -05:00
|
|
|
"INSERT INTO ticket_comments (ticket_id, user_id, user_name, comment_text, markdown_enabled) VALUES (?, ?, ?, ?, 1)"
|
2026-09-11 21:41:57 -04:00
|
|
|
);
|
2026-11-25 20:22:06 -05:00
|
|
|
$commentStmt->bind_param("siss", $existingId, $userId, $commentAuthor, $commentText);
|
2026-09-11 21:41:57 -04:00
|
|
|
$commentStmt->execute();
|
|
|
|
|
$commentStmt->close();
|
|
|
|
|
|
|
|
|
|
if ($reopenStatus !== null) {
|
|
|
|
|
$auditLog->log($userId, 'update', 'ticket', $existingId, [
|
|
|
|
|
'status' => ['from' => 'Closed', 'to' => $reopenStatus],
|
2026-11-25 20:22:06 -05:00
|
|
|
'reason' => "auto-reopened by {$source} (issue recurred)",
|
2026-09-11 21:41:57 -04:00
|
|
|
]);
|
|
|
|
|
|
|
|
|
|
// Ticket reopened — refresh dashboard stats.
|
2026-07-10 16:11:26 -04:00
|
|
|
(new StatsModel($conn))->invalidateCache();
|
2026-09-11 21:41:57 -04:00
|
|
|
} else {
|
|
|
|
|
$auditLog->log($userId, 'update', 'ticket', $existingId, [
|
2026-11-25 20:22:06 -05:00
|
|
|
'reason' => "{$source} recurrence detected but no valid reopen transition configured; ticket left Closed",
|
2026-09-11 21:41:57 -04:00
|
|
|
]);
|
2026-04-06 18:55:15 -04:00
|
|
|
}
|
|
|
|
|
|
2026-09-11 21:41:57 -04:00
|
|
|
$conn->commit();
|
2026-09-11 11:42:21 -04:00
|
|
|
Database::close();
|
2026-09-11 21:41:57 -04:00
|
|
|
|
|
|
|
|
if ($reopenStatus !== null) {
|
|
|
|
|
require_once __DIR__ . '/helpers/NotificationHelper.php';
|
|
|
|
|
NotificationHelper::sendTicketNotification($existingId, [
|
|
|
|
|
'title' => $title,
|
|
|
|
|
'priority' => $priority,
|
|
|
|
|
'category' => $category,
|
|
|
|
|
'type' => $type,
|
|
|
|
|
'status' => $reopenStatus,
|
|
|
|
|
], 'automated');
|
|
|
|
|
}
|
|
|
|
|
|
2026-04-06 17:40:36 -04:00
|
|
|
echo json_encode([
|
2026-09-11 21:41:57 -04:00
|
|
|
'success' => true,
|
|
|
|
|
'ticket_id' => $existingId,
|
|
|
|
|
'message' => $reopenStatus !== null
|
|
|
|
|
? 'Existing closed ticket reopened'
|
|
|
|
|
: 'Recurrence noted; ticket left Closed (no valid workflow transition configured)',
|
|
|
|
|
'action' => $reopenStatus !== null ? 'reopened' : 'recurrence_noted',
|
2026-04-06 17:40:36 -04:00
|
|
|
]);
|
|
|
|
|
exit;
|
|
|
|
|
}
|
|
|
|
|
|
2026-11-25 20:22:06 -05:00
|
|
|
// No ticket holds this hash, or the one that does closed longer ago than
|
|
|
|
|
// the reopen window (#123): create a new one. In the second case the new
|
|
|
|
|
// ticket is a recurrence: it takes over the hash (unique, so the old
|
|
|
|
|
// ticket gives it up), records the old ticket in recurrence_of, and is
|
|
|
|
|
// linked relates_to it with a history comment.
|
|
|
|
|
//
|
|
|
|
|
// Still inside the transaction opened above, so a concurrent request for
|
|
|
|
|
// the same hash is blocked on its own SELECT ... FOR UPDATE until this one
|
|
|
|
|
// commits or rolls back rather than racing this INSERT.
|
2026-09-11 21:41:57 -04:00
|
|
|
//
|
|
|
|
|
// Note on FOR UPDATE over a not-yet-existing key: InnoDB's gap lock in that
|
2026-11-25 20:22:06 -05:00
|
|
|
// case is a shared lock, not exclusive, so two concurrent transactions can
|
2026-09-11 21:41:57 -04:00
|
|
|
// both acquire it and both reach this INSERT. The conflict only surfaces
|
|
|
|
|
// when they each request the insert-intention lock for the same gap,
|
|
|
|
|
// which InnoDB resolves as a deadlock (error 1213), not by blocking one
|
|
|
|
|
// of the SELECTs. The outer loop above retries that case: the loser rolls
|
|
|
|
|
// back and re-runs its own SELECT ... FOR UPDATE, which by then finds the
|
|
|
|
|
// winner's committed row and takes the update/escalate branch instead.
|
2026-11-25 20:22:06 -05:00
|
|
|
$previous = $existing; // a Closed ticket outside the window, or null
|
|
|
|
|
$previousId = $previous['ticket_id'] ?? null;
|
2026-09-11 21:41:57 -04:00
|
|
|
|
2026-11-25 20:22:06 -05:00
|
|
|
// A ticket_id that is free, so a 1062 on INSERT below can only be the
|
|
|
|
|
// unique hash, and with the FOR UPDATE lock above only in the unlikely
|
|
|
|
|
// case of a hash collision between two genuinely different reports.
|
|
|
|
|
$ticket_id = AutoTicketService::newTicketId($conn);
|
2026-09-11 21:41:57 -04:00
|
|
|
if ($ticket_id === null) {
|
|
|
|
|
$conn->rollback();
|
2026-11-25 20:22:06 -05:00
|
|
|
error_log('create_ticket_api: failed to generate a unique ticket_id');
|
2026-09-11 21:41:57 -04:00
|
|
|
http_response_code(500);
|
|
|
|
|
echo json_encode(['success' => false, 'error' => 'Internal server error']);
|
|
|
|
|
exit;
|
2026-09-11 12:37:46 -04:00
|
|
|
}
|
2026-09-11 21:41:57 -04:00
|
|
|
|
|
|
|
|
try {
|
2026-11-25 20:22:06 -05:00
|
|
|
if ($previousId !== null) {
|
|
|
|
|
AutoTicketService::releaseHash($conn, $previousId);
|
|
|
|
|
}
|
|
|
|
|
AutoTicketService::insert($conn, [
|
|
|
|
|
'ticket_id' => $ticket_id,
|
|
|
|
|
'title' => $title,
|
|
|
|
|
'description' => $description,
|
|
|
|
|
'status' => $status,
|
|
|
|
|
'priority' => $priority,
|
|
|
|
|
'category' => $category,
|
|
|
|
|
'type' => $type,
|
|
|
|
|
'hash' => $ticketHash,
|
|
|
|
|
'created_by' => $userId,
|
|
|
|
|
'source' => $source,
|
|
|
|
|
'dedup_key' => $dedupKey ?? ($previous['dedup_key'] ?? null),
|
|
|
|
|
'recurrence_of' => $previousId,
|
|
|
|
|
]);
|
2026-09-11 21:41:57 -04:00
|
|
|
} catch (mysqli_sql_exception $e) {
|
|
|
|
|
$conn->rollback();
|
|
|
|
|
if (in_array($e->getCode(), [1213, 1205], true) && $dedupAttempt < $maxDedupAttempts) {
|
|
|
|
|
// Deadlock (1213) or lock wait timeout (1205) from a concurrent
|
2026-11-25 20:22:06 -05:00
|
|
|
// insert into the same not-yet-existing hash gap: see the note
|
2026-09-11 21:41:57 -04:00
|
|
|
// above. Retry: the next iteration's own SELECT ... FOR UPDATE
|
|
|
|
|
// will find whichever side won and take the update/escalate path.
|
|
|
|
|
continue;
|
|
|
|
|
}
|
|
|
|
|
if ($e->getCode() === 1062) {
|
2026-11-25 20:22:06 -05:00
|
|
|
// Defensive: only a genuine hash collision between two different
|
|
|
|
|
// reports can get here now that the SELECT above takes FOR UPDATE.
|
2026-09-11 21:41:57 -04:00
|
|
|
echo json_encode(['success' => false, 'error' => 'Duplicate ticket']);
|
|
|
|
|
} else {
|
|
|
|
|
error_log('create_ticket_api: insert failed: ' . $e->getMessage());
|
|
|
|
|
http_response_code(500);
|
|
|
|
|
echo json_encode(['success' => false, 'error' => 'Internal server error']);
|
|
|
|
|
}
|
|
|
|
|
exit;
|
|
|
|
|
}
|
2026-04-06 17:40:36 -04:00
|
|
|
|
2026-11-25 20:22:06 -05:00
|
|
|
$auditLog->logTicketCreate($userId, $ticket_id, [
|
|
|
|
|
'title' => $title,
|
|
|
|
|
'priority' => $priority,
|
|
|
|
|
'category' => $category,
|
|
|
|
|
'type' => $type,
|
|
|
|
|
]);
|
2026-07-10 12:26:39 -04:00
|
|
|
|
2026-11-25 20:22:06 -05:00
|
|
|
if ($previousId !== null) {
|
|
|
|
|
AutoTicketService::linkRecurrence($conn, $ticket_id, $previousId, (int)$userId);
|
|
|
|
|
$historyText = AutoTicketService::historyComment($conn, $ticket_id, $previousId, $previous['closed_at'] ?? null);
|
|
|
|
|
$commentStmt = $conn->prepare(
|
|
|
|
|
"INSERT INTO ticket_comments (ticket_id, user_id, user_name, comment_text, markdown_enabled) VALUES (?, ?, ?, ?, 1)"
|
|
|
|
|
);
|
|
|
|
|
$commentStmt->bind_param("siss", $ticket_id, $userId, $commentAuthor, $historyText);
|
|
|
|
|
$commentStmt->execute();
|
|
|
|
|
$commentStmt->close();
|
|
|
|
|
$auditLog->log($userId, 'update', 'ticket', $previousId, [
|
|
|
|
|
'reason' => "{$source} reported this problem again after the "
|
|
|
|
|
. AutoTicketService::reopenWindowDays() . "-day reopen window; continued in {$ticket_id}",
|
2026-09-11 21:41:57 -04:00
|
|
|
]);
|
2026-04-06 17:40:36 -04:00
|
|
|
}
|
2026-11-25 20:22:06 -05:00
|
|
|
|
|
|
|
|
// New ticket created: refresh dashboard stats.
|
|
|
|
|
(new StatsModel($conn))->invalidateCache();
|
|
|
|
|
|
|
|
|
|
$conn->commit();
|
|
|
|
|
Database::close();
|
|
|
|
|
|
|
|
|
|
require_once __DIR__ . '/helpers/NotificationHelper.php';
|
|
|
|
|
NotificationHelper::sendTicketNotification($ticket_id, [
|
|
|
|
|
'title' => $title,
|
|
|
|
|
'priority' => $priority,
|
|
|
|
|
'category' => $category,
|
|
|
|
|
'type' => $type,
|
|
|
|
|
'status' => $status,
|
|
|
|
|
], 'automated');
|
|
|
|
|
|
|
|
|
|
$response = [
|
|
|
|
|
'success' => true,
|
|
|
|
|
'ticket_id' => $ticket_id,
|
|
|
|
|
'message' => $previousId !== null
|
|
|
|
|
? "New ticket for a recurrence of {$previousId}"
|
|
|
|
|
: 'Ticket created successfully',
|
|
|
|
|
'action' => $previousId !== null ? 'new_recurrence' : 'created',
|
|
|
|
|
];
|
|
|
|
|
if ($previousId !== null) {
|
|
|
|
|
$response['previous_ticket_id'] = $previousId;
|
|
|
|
|
}
|
|
|
|
|
echo json_encode($response);
|
|
|
|
|
// Done: only the deadlock `continue` above may run the loop again.
|
2026-09-25 15:34:44 -04:00
|
|
|
// Falling through re-entered it on a closed connection, appending a
|
|
|
|
|
// 500 error body after the success response for every new ticket.
|
|
|
|
|
exit;
|
2024-11-30 19:48:01 -05:00
|
|
|
}
|