From 7228709ff6aeb79f1f03c56b8c830c2d0f3758fc Mon Sep 17 00:00:00 2001 From: Jared Vititoe Date: Thu, 27 Feb 2025 21:37:38 -0500 Subject: [PATCH] Ticket Deduplication with the hwmonDaemon script --- .gitignore | 3 ++- create_ticket_api.php | 56 +++++++++++++++++++++++++++++++++++++++---- 2 files changed, 54 insertions(+), 5 deletions(-) diff --git a/.gitignore b/.gitignore index 2eea525..7ce1d67 100755 --- a/.gitignore +++ b/.gitignore @@ -1 +1,2 @@ -.env \ No newline at end of file +.env +debug.log \ No newline at end of file diff --git a/create_ticket_api.php b/create_ticket_api.php index f845208..f8a824b 100644 --- a/create_ticket_api.php +++ b/create_ticket_api.php @@ -41,6 +41,53 @@ if ($conn->connect_error) { exit; } +// Create tickets table with hash column if not exists +$createTableSQL = "CREATE TABLE IF NOT EXISTS tickets ( + id INT AUTO_INCREMENT PRIMARY KEY, + ticket_id VARCHAR(9) NOT NULL, + title VARCHAR(255) NOT NULL, + hash VARCHAR(64) NOT NULL, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + UNIQUE KEY unique_hash (hash) +)"; + +$conn->query($createTableSQL); + +// Generate hash from stable components +function generateTicketHash($data) { + $stableComponents = [ + 'title' => $data['title'], + // Extract metadata tags from title + 'tags' => array_filter( + explode(']', str_replace(['[', ']'], '', $data['title'])), + 'strlen' + ) + ]; + + // Sort components for consistent hashing + sort($stableComponents['tags']); + + return hash('sha256', json_encode($stableComponents, JSON_UNESCAPED_SLASHES)); +} + +// Check for duplicate tickets +$ticketHash = generateTicketHash($data); +$checkDuplicateSQL = "SELECT ticket_id FROM tickets WHERE hash = ? AND created_at > DATE_SUB(NOW(), INTERVAL 24 HOUR)"; +$checkStmt = $conn->prepare($checkDuplicateSQL); +$checkStmt->bind_param("s", $ticketHash); +$checkStmt->execute(); +$result = $checkStmt->get_result(); + +if ($result->num_rows > 0) { + $existingTicket = $result->fetch_assoc(); + echo json_encode([ + 'success' => false, + 'error' => 'Duplicate ticket', + 'existing_ticket_id' => $existingTicket['ticket_id'] + ]); + exit; +} + // Force JSON content type for all incoming requests header('Content-Type: application/json'); @@ -57,8 +104,8 @@ if (!$data) { $ticket_id = sprintf('%09d', mt_rand(1, 999999999)); // Prepare insert query -$sql = "INSERT INTO tickets (ticket_id, title, description, status, priority, category, type) - VALUES (?, ?, ?, ?, ?, ?, ?)"; +$sql = "INSERT INTO tickets (ticket_id, title, description, status, priority, category, type, hash) + VALUES (?, ?, ?, ?, ?, ?, ?, ?)"; $stmt = $conn->prepare($sql); // First, store all values in variables @@ -71,14 +118,15 @@ $type = $data['type'] ?? 'Issue'; // Then use the variables in bind_param $stmt->bind_param( - "sssssss", + "ssssssss", $ticket_id, $title, $description, $status, $priority, $category, - $type + $type, + $ticketHash ); if ($stmt->execute()) {