Files
tinker_tickets/controllers/TicketController.php
Jared Vititoe 353ce83a36 Feature 4: Implement Ticket Templates
Add ticket template system for quick ticket creation:

- Created TemplateModel.php with full CRUD operations for templates
- Added get_template.php API endpoint to fetch template data
- Updated TicketController to load templates in create() method
- Modified CreateTicketView.php to include template selector dropdown
- Added loadTemplate() JavaScript function to populate form fields
- Templates include: title, description, category, type, and default priority
- Database already seeded with default templates (Hardware Failure, Software Installation, Network Issue, Maintenance Request)

Users can now select from predefined templates when creating tickets, speeding up common ticket creation workflows.

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-01-01 19:00:42 -05:00

269 lines
9.6 KiB
PHP

<?php
// Use absolute paths for model includes
require_once dirname(__DIR__) . '/models/TicketModel.php';
require_once dirname(__DIR__) . '/models/CommentModel.php';
require_once dirname(__DIR__) . '/models/AuditLogModel.php';
require_once dirname(__DIR__) . '/models/UserModel.php';
require_once dirname(__DIR__) . '/models/WorkflowModel.php';
require_once dirname(__DIR__) . '/models/TemplateModel.php';
class TicketController {
private $ticketModel;
private $commentModel;
private $auditLogModel;
private $userModel;
private $workflowModel;
private $templateModel;
private $envVars;
public function __construct($conn) {
$this->ticketModel = new TicketModel($conn);
$this->commentModel = new CommentModel($conn);
$this->auditLogModel = new AuditLogModel($conn);
$this->userModel = new UserModel($conn);
$this->workflowModel = new WorkflowModel($conn);
$this->templateModel = new TemplateModel($conn);
// Load environment variables for Discord webhook
$envPath = dirname(__DIR__) . '/.env';
$this->envVars = [];
if (file_exists($envPath)) {
$lines = file($envPath, FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
foreach ($lines as $line) {
if (strpos($line, '=') !== false && strpos($line, '#') !== 0) {
list($key, $value) = explode('=', $line, 2);
$key = trim($key);
$value = trim($value);
// Remove surrounding quotes if present
if ((substr($value, 0, 1) === '"' && substr($value, -1) === '"') ||
(substr($value, 0, 1) === "'" && substr($value, -1) === "'")) {
$value = substr($value, 1, -1);
}
$this->envVars[$key] = $value;
}
}
}
}
public function view($id) {
// Get current user
$currentUser = $GLOBALS['currentUser'] ?? null;
$userId = $currentUser['user_id'] ?? null;
// Get ticket data
$ticket = $this->ticketModel->getTicketById($id);
if (!$ticket) {
header("HTTP/1.0 404 Not Found");
echo "Ticket not found";
return;
}
// Log ticket view to audit log
if (isset($GLOBALS['auditLog']) && $userId) {
$GLOBALS['auditLog']->logTicketView($userId, $id);
}
// Get comments for this ticket using CommentModel
$comments = $this->commentModel->getCommentsByTicketId($id);
// Get timeline for this ticket
$timeline = $this->auditLogModel->getTicketTimeline($id);
// Get all users for assignment dropdown
$allUsers = $this->userModel->getAllUsers();
// Get allowed status transitions for this ticket
$allowedTransitions = $this->workflowModel->getAllowedTransitions($ticket['status']);
// Load the view
include dirname(__DIR__) . '/views/TicketView.php';
}
public function create() {
// Get current user
$currentUser = $GLOBALS['currentUser'] ?? null;
$userId = $currentUser['user_id'] ?? null;
// Check if form was submitted
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
$ticketData = [
'title' => $_POST['title'] ?? '',
'description' => $_POST['description'] ?? '',
'priority' => $_POST['priority'] ?? '4',
'category' => $_POST['category'] ?? 'General',
'type' => $_POST['type'] ?? 'Issue'
];
// Validate input
if (empty($ticketData['title'])) {
$error = "Title is required";
$templates = $this->templateModel->getAllTemplates();
include dirname(__DIR__) . '/views/CreateTicketView.php';
return;
}
// Create ticket with user tracking
$result = $this->ticketModel->createTicket($ticketData, $userId);
if ($result['success']) {
// Log ticket creation to audit log
if (isset($GLOBALS['auditLog']) && $userId) {
$GLOBALS['auditLog']->logTicketCreate($userId, $result['ticket_id'], $ticketData);
}
// Send Discord webhook notification for new ticket
$this->sendDiscordWebhook($result['ticket_id'], $ticketData);
// Redirect to the new ticket
header("Location: " . $GLOBALS['config']['BASE_URL'] . "/ticket/" . $result['ticket_id']);
exit;
} else {
$error = $result['error'];
$templates = $this->templateModel->getAllTemplates();
include dirname(__DIR__) . '/views/CreateTicketView.php';
return;
}
} else {
// Get all templates for the template selector
$templates = $this->templateModel->getAllTemplates();
// Display the create ticket form
include dirname(__DIR__) . '/views/CreateTicketView.php';
}
}
public function update($id) {
// Get current user
$currentUser = $GLOBALS['currentUser'] ?? null;
$userId = $currentUser['user_id'] ?? null;
// Check if this is an AJAX request
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
// For AJAX requests, get JSON data
$input = file_get_contents('php://input');
$data = json_decode($input, true);
// Add ticket_id to the data
$data['ticket_id'] = $id;
// Validate input data
if (empty($data['title'])) {
header('Content-Type: application/json');
echo json_encode([
'success' => false,
'error' => 'Title cannot be empty'
]);
return;
}
// Update ticket with user tracking
$result = $this->ticketModel->updateTicket($data, $userId);
// Log ticket update to audit log
if ($result && isset($GLOBALS['auditLog']) && $userId) {
$GLOBALS['auditLog']->logTicketUpdate($userId, $id, $data);
}
// Return JSON response
header('Content-Type: application/json');
if ($result) {
echo json_encode([
'success' => true,
'status' => $data['status']
]);
} else {
echo json_encode([
'success' => false,
'error' => 'Failed to update ticket'
]);
}
} else {
// For direct access, redirect to view
header("Location: " . $GLOBALS['config']['BASE_URL'] . "/ticket/$id");
exit;
}
}
private function sendDiscordWebhook($ticketId, $ticketData) {
if (!isset($this->envVars['DISCORD_WEBHOOK_URL']) || empty($this->envVars['DISCORD_WEBHOOK_URL'])) {
error_log("Discord webhook URL not configured, skipping webhook for ticket creation");
return;
}
$webhookUrl = $this->envVars['DISCORD_WEBHOOK_URL'];
// Create ticket URL
$ticketUrl = "http://t.lotusguild.org/ticket/$ticketId";
// Map priorities to Discord colors
$priorityColors = [
1 => 0xff4d4d, // Red
2 => 0xffa726, // Orange
3 => 0x42a5f5, // Blue
4 => 0x66bb6a, // Green
5 => 0x9e9e9e // Gray
];
$priority = (int)($ticketData['priority'] ?? 4);
$color = $priorityColors[$priority] ?? 0x3498db;
$embed = [
'title' => '🎫 New Ticket Created',
'description' => "**#{$ticketId}** - " . $ticketData['title'],
'url' => $ticketUrl,
'color' => $color,
'fields' => [
[
'name' => 'Priority',
'value' => 'P' . $priority,
'inline' => true
],
[
'name' => 'Category',
'value' => $ticketData['category'] ?? 'General',
'inline' => true
],
[
'name' => 'Type',
'value' => $ticketData['type'] ?? 'Issue',
'inline' => true
],
[
'name' => 'Status',
'value' => $ticketData['status'] ?? 'Open',
'inline' => true
]
],
'footer' => [
'text' => 'Tinker Tickets'
],
'timestamp' => date('c')
];
$payload = [
'embeds' => [$embed]
];
// Send webhook
$ch = curl_init($webhookUrl);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
curl_setopt($ch, CURLOPT_TIMEOUT, 10);
$webhookResult = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
$curlError = curl_error($ch);
curl_close($ch);
if ($curlError) {
error_log("Discord webhook cURL error: $curlError");
} else {
error_log("Discord webhook sent for new ticket. HTTP Code: $httpCode");
}
}
}
?>