From 57d572a15e04e3ec5dea4f53dc13566ee9b240ca Mon Sep 17 00:00:00 2001 From: Jared Vititoe Date: Thu, 1 Jan 2026 19:45:49 -0500 Subject: [PATCH] readme and css updates --- Claude.md | 1133 ++++++++++++++++++++------------------ README.md | 289 +++++++++- assets/css/dashboard.css | 56 ++ assets/css/ticket.css | 77 +++ 4 files changed, 982 insertions(+), 573 deletions(-) diff --git a/Claude.md b/Claude.md index 5e31014..a22a836 100644 --- a/Claude.md +++ b/Claude.md @@ -1,128 +1,253 @@ # Tinker Tickets - Project Documentation for AI Assistants +## Project Status (January 2026) + +**Current Phase**: All 5 core features implemented and deployed. Ready for ANSI Art redesign. + +**Recent Completion**: +- ✅ Activity Timeline (Feature 1) +- ✅ Ticket Assignment (Feature 2) +- ✅ Status Transitions with Workflows (Feature 3) +- ✅ Ticket Templates (Feature 4) +- ✅ Bulk Actions - Admin Only (Feature 5) + +**Next Priority**: 🎨 ANSI Art Redesign (major visual overhaul) + ## Project Overview -Tinker Tickets is a lightweight, self-hosted ticket management system built for managing data center infrastructure issues. It features automatic ticket creation via hardware monitoring integration, Discord notifications, and a clean web interface. +Tinker Tickets is a feature-rich, self-hosted ticket management system built for managing data center infrastructure issues. It features SSO integration with Authelia/LLDAP, workflow management, Discord notifications, and a comprehensive web interface. **Tech Stack:** -- Backend: PHP 8+ with MySQLi +- Backend: PHP 7.4+ with MySQLi - Frontend: Vanilla JavaScript, CSS3 -- Database: MariaDB (on separate LXC: 10.10.10.???) -- Web Server: Nginx on production (10.10.10.45) +- Database: MariaDB on separate LXC (10.10.10.50) +- Web Server: Apache on production (10.10.10.45) +- Authentication: Authelia SSO with LLDAP backend - External Libraries: marked.js (Markdown rendering) **Production Environment:** -- **Primary URL**: https://t.lotusguild.org -- **Beta URL**: https://beta.t.lotusguild.org (React port - in development) -- **Web Server**: Nginx at 10.10.10.45 (`/var/www/html/tinkertickets`) -- **Database**: MariaDB on separate LXC (`ticketing_system` database) +- **Primary URL**: http://t.lotusguild.org +- **Web Server**: Apache at 10.10.10.45 (`/root/code/tinker_tickets`) +- **Database**: MariaDB at 10.10.10.50 (`ticketing_system` database) +- **Authentication**: Authelia provides SSO via headers ## Architecture -### Project Structure +### MVC Pattern +``` +Controllers → Models → Database + ↓ + Views +``` + +### Project Structure (Updated) ``` /tinker_tickets/ -├── api/ # API endpoints (standalone PHP files) -│ ├── add_comment.php # POST: Add comment to ticket -│ └── update_ticket.php # POST: Update ticket fields (partial updates) -├── assets/ # Static assets +├── api/ # API endpoints +│ ├── add_comment.php # POST: Add comment +│ ├── assign_ticket.php # POST: Assign ticket to user (NEW) +│ ├── bulk_operation.php # POST: Bulk operations - admin only (NEW) +│ ├── get_template.php # GET: Fetch ticket template (NEW) +│ ├── get_users.php # GET: Get user list (NEW) +│ └── update_ticket.php # POST: Update ticket (workflow validation) +├── assets/ │ ├── css/ -│ │ ├── dashboard.css # Shared + dashboard styles -│ │ └── ticket.css # Ticket page styles +│ │ ├── dashboard.css # Shared + dashboard + bulk actions +│ │ └── ticket.css # Ticket + timeline + dark mode fixes │ ├── js/ -│ │ ├── dashboard.js # Dashboard + hamburger menu -│ │ └── ticket.js # Ticket interactions +│ │ ├── dashboard.js # Dashboard + hamburger + bulk actions + templates +│ │ └── ticket.js # Ticket + comments + status updates + assignment │ └── images/ │ └── favicon.png ├── config/ -│ └── config.php # Config + .env loading -├── controllers/ # MVC Controllers -│ ├── CommentController.php # Comment operations -│ ├── DashboardController.php # Dashboard/listing -│ └── TicketController.php # Ticket CRUD + webhooks -├── models/ # Data models -│ ├── CommentModel.php # Comment data access -│ └── TicketModel.php # Ticket data access -├── views/ # PHP templates -│ ├── CreateTicketView.php # Ticket creation form -│ ├── DashboardView.php # Main listing page -│ └── TicketView.php # Single ticket view -├── .env # Environment variables (GITIGNORED) -├── .gitignore -├── create_ticket_api.php # External API for hwmonDaemon -├── deploy.sh # Legacy manual deploy (not used) -├── index.php # Main entry point + router -└── README.md +│ └── config.php # Config + .env loading +├── controllers/ # MVC Controllers +│ ├── DashboardController.php # Dashboard with assigned_to column +│ └── TicketController.php # Ticket CRUD + timeline + templates +├── models/ # Data models +│ ├── AuditLogModel.php # Audit logging + timeline +│ ├── BulkOperationsModel.php # Bulk operations tracking (NEW) +│ ├── CommentModel.php # Comment data access +│ ├── TemplateModel.php # Ticket templates (NEW) +│ ├── TicketModel.php # Ticket CRUD + assignment +│ ├── UserModel.php # User management (NEW) +│ └── WorkflowModel.php # Status transition workflows (NEW) +├── views/ # PHP templates +│ ├── CreateTicketView.php # Ticket creation with templates +│ ├── DashboardView.php # Dashboard with bulk actions + assigned column +│ └── TicketView.php # Ticket view with timeline + assignment +├── migrations/ # Database migrations +│ ├── 001_initial_schema.sql +│ ├── 007_add_ticket_assignment.sql # Ticket assignment +│ ├── 008_add_status_workflows.sql # Workflow rules +│ ├── 009_add_ticket_templates.sql # Ticket templates +│ ├── 010_add_bulk_operations.sql # Bulk operations +│ └── 011_remove_view_tracking.sql # Remove view audit logs +├── .env # Environment variables (GITIGNORED) +├── Claude.md # This file +├── README.md # User documentation +├── index.php # Dashboard entry point +└── ticket.php # Ticket view/create router ``` -### Routing System (`index.php`) +## Database Schema (Updated) -Simple switch-based router: -- `/` → Dashboard -- `/ticket/{id}` → View ticket -- `/ticket/create` → Create ticket form -- `/api/update_ticket.php` → Update ticket (AJAX) -- `/api/add_comment.php` → Add comment (AJAX) +**Database**: `ticketing_system` at 10.10.10.50 +**User**: `tinkertickets` +**Connection**: All APIs create their own connections via config.php -**Important Notes:** -- API routes handle their own database connections -- Page routes receive connection from index.php -- Legacy routes redirect to new URLs +### Core Tables -## Database Schema - -**Database Name:** `ticketing_system` (NOT `tinkertickets`) - -### `tickets` Table +#### `tickets` Table (Updated) ```sql CREATE TABLE tickets ( - ticket_id VARCHAR(9) PRIMARY KEY, -- 9-digit format with leading zeros + ticket_id INT AUTO_INCREMENT PRIMARY KEY, title VARCHAR(255) NOT NULL, description TEXT, - status VARCHAR(50) DEFAULT 'Open', -- 'Open', 'Closed', 'In Progress', 'Pending' - priority INT DEFAULT 4, -- 1=Critical, 2=High, 3=Medium, 4=Low, 5=Lowest - category VARCHAR(50) DEFAULT 'General', -- Hardware, Software, Network, Security, General - type VARCHAR(50) DEFAULT 'Issue', -- Maintenance, Install, Task, Upgrade, Issue - hash VARCHAR(64), -- For duplicate detection (hwmonDaemon) + status VARCHAR(50) DEFAULT 'Open', + priority INT DEFAULT 4, + category VARCHAR(50) DEFAULT 'General', + type VARCHAR(50) DEFAULT 'Issue', + created_by INT, -- User who created + updated_by INT, -- User who last updated + assigned_to INT, -- User assigned to (NEW) created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, - updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP + updated_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP, + FOREIGN KEY (created_by) REFERENCES users(user_id), + FOREIGN KEY (updated_by) REFERENCES users(user_id), + FOREIGN KEY (assigned_to) REFERENCES users(user_id) ON DELETE SET NULL, + INDEX idx_status (status), + INDEX idx_assigned_to (assigned_to) ) ENGINE=InnoDB; ``` -### `ticket_comments` Table +#### `users` Table (SSO Integration) ```sql -CREATE TABLE ticket_comments ( - comment_id INT AUTO_INCREMENT PRIMARY KEY, - ticket_id VARCHAR(10), - user_name VARCHAR(50), - comment_text TEXT, - markdown_enabled TINYINT(1) DEFAULT 0, - created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, - FOREIGN KEY (ticket_id) REFERENCES tickets(ticket_id) +CREATE TABLE users ( + user_id INT AUTO_INCREMENT PRIMARY KEY, + username VARCHAR(100) UNIQUE NOT NULL, + display_name VARCHAR(255), + email VARCHAR(255), + is_admin BOOLEAN DEFAULT FALSE, + last_login TIMESTAMP NULL, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP ) ENGINE=InnoDB; ``` -**Key Points:** -- Ticket IDs are VARCHAR (9-digit format with leading zeros) -- Status ENUM-like validation in application layer -- Hash field used for duplicate detection by hwmonDaemon -- Comments support optional Markdown rendering +#### `comments` Table +```sql +CREATE TABLE comments ( + comment_id INT AUTO_INCREMENT PRIMARY KEY, + ticket_id INT NOT NULL, + user_id INT, + comment_text TEXT NOT NULL, + markdown_enabled BOOLEAN DEFAULT FALSE, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + FOREIGN KEY (ticket_id) REFERENCES tickets(ticket_id) ON DELETE CASCADE, + FOREIGN KEY (user_id) REFERENCES users(user_id), + INDEX idx_ticket_id (ticket_id) +) ENGINE=InnoDB; +``` -## API Endpoints +#### `audit_log` Table (Activity Timeline) +```sql +CREATE TABLE audit_log ( + log_id INT AUTO_INCREMENT PRIMARY KEY, + user_id INT, + action_type VARCHAR(50) NOT NULL, -- 'create', 'update', 'comment', 'assign', etc. + entity_type VARCHAR(50) NOT NULL, -- 'ticket', 'comment' + entity_id INT NOT NULL, -- ticket_id or comment_id + details JSON, -- JSON details of what changed + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + FOREIGN KEY (user_id) REFERENCES users(user_id), + INDEX idx_entity (entity_type, entity_id), + INDEX idx_user (user_id), + INDEX idx_action (action_type) +) ENGINE=InnoDB; +``` + +#### `status_transitions` Table (Workflow Rules) +```sql +CREATE TABLE status_transitions ( + transition_id INT AUTO_INCREMENT PRIMARY KEY, + from_status VARCHAR(50) NOT NULL, + to_status VARCHAR(50) NOT NULL, + requires_comment BOOLEAN DEFAULT FALSE, -- Transition requires comment + requires_admin BOOLEAN DEFAULT FALSE, -- Transition requires admin + is_active BOOLEAN DEFAULT TRUE, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + UNIQUE KEY unique_transition (from_status, to_status), + INDEX idx_from_status (from_status) +) ENGINE=InnoDB; +``` + +Default transitions: +```sql +-- Open → In Progress, Closed, Resolved +-- In Progress → Open, Closed, Resolved +-- Resolved → Closed, In Progress +-- Closed → Open, In Progress (requires comment) +``` + +#### `ticket_templates` Table +```sql +CREATE TABLE ticket_templates ( + template_id INT AUTO_INCREMENT PRIMARY KEY, + template_name VARCHAR(100) NOT NULL, + title_template VARCHAR(255) NOT NULL, + description_template TEXT NOT NULL, + category VARCHAR(50), + type VARCHAR(50), + default_priority INT DEFAULT 4, + created_by INT, + is_active BOOLEAN DEFAULT TRUE, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + FOREIGN KEY (created_by) REFERENCES users(user_id), + INDEX idx_template_name (template_name) +) ENGINE=InnoDB; +``` + +Default templates: Hardware Failure, Software Installation, Network Issue, Maintenance Request + +#### `bulk_operations` Table +```sql +CREATE TABLE bulk_operations ( + operation_id INT AUTO_INCREMENT PRIMARY KEY, + operation_type VARCHAR(50) NOT NULL, -- 'bulk_close', 'bulk_assign', 'bulk_priority' + ticket_ids TEXT NOT NULL, -- Comma-separated ticket IDs + performed_by INT NOT NULL, + parameters JSON, -- Operation parameters + status VARCHAR(20) DEFAULT 'pending', + total_tickets INT, + processed_tickets INT DEFAULT 0, + failed_tickets INT DEFAULT 0, + created_at TIMESTAMP DEFAULT CURRENT_TIMESTAMP, + completed_at TIMESTAMP NULL, + FOREIGN KEY (performed_by) REFERENCES users(user_id), + INDEX idx_performed_by (performed_by), + INDEX idx_created_at (created_at) +) ENGINE=InnoDB; +``` + +## API Endpoints (Updated) + +### Authentication +All API endpoints check: `$_SESSION['user']['user_id']` for authentication. +Admin-only endpoints check: `$_SESSION['user']['is_admin']`. ### POST `/api/update_ticket.php` -Updates ticket fields (supports partial updates). +Updates ticket with workflow validation. **Request:** ```json { - "ticket_id": 123456789, - "status": "In Progress", // Optional - "priority": 2, // Optional (1-5) - "title": "Updated title", // Optional - "description": "...", // Optional - "category": "Software", // Optional - "type": "Task" // Optional + "ticket_id": 123, + "status": "In Progress", // Validated against workflow rules + "priority": 2, + "title": "Updated title", + "description": "...", + "category": "Software", + "type": "Task" } ``` @@ -137,29 +262,102 @@ Updates ticket fields (supports partial updates). ``` **Features:** -- Merges updates with existing ticket data (partial updates) -- Validates status against allowed values -- Validates priority range (1-5) -- Sends Discord webhook on changes -- Debug logging to `/tmp/api_debug.log` +- Workflow validation via WorkflowModel +- Partial updates (only send changed fields) +- User tracking (updated_by) +- Discord webhook notifications +- Audit logging -**Discord Webhook:** -- Triggered on ticket updates -- Shows field changes (old → new) -- Color-coded by priority -- Links to ticket URL -- Only sends if changes detected +### POST `/api/assign_ticket.php` (NEW) +Assigns ticket to a user. + +**Request:** +```json +{ + "ticket_id": 123, + "assigned_to": 5 // user_id, or null to unassign +} +``` + +**Response:** +```json +{ + "success": true +} +``` + +### GET `/api/get_users.php` (NEW) +Returns list of all users for assignment dropdowns. + +**Response:** +```json +{ + "success": true, + "users": [ + { + "user_id": 1, + "username": "jared", + "display_name": "Jared Vititoe", + "is_admin": true + } + ] +} +``` + +### GET `/api/get_template.php?template_id=1` (NEW) +Fetches a ticket template. + +**Response:** +```json +{ + "success": true, + "template": { + "template_id": 1, + "template_name": "Hardware Failure", + "title_template": "Hardware Failure: [Device Name]", + "description_template": "Device: \nIssue: \n...", + "category": "Hardware", + "type": "Problem", + "default_priority": 2 + } +} +``` + +### POST `/api/bulk_operation.php` (NEW - ADMIN ONLY) +Performs bulk operations on tickets. + +**Request:** +```json +{ + "operation_type": "bulk_close", // or 'bulk_assign', 'bulk_priority' + "ticket_ids": [123, 456, 789], + "parameters": { // For bulk_assign or bulk_priority + "assigned_to": 5, // For bulk_assign + "priority": 2 // For bulk_priority + } +} +``` + +**Response:** +```json +{ + "success": true, + "operation_id": 42, + "processed": 3, + "failed": 0, + "message": "Bulk operation completed: 3 succeeded, 0 failed" +} +``` ### POST `/api/add_comment.php` -Adds a comment to a ticket. +Adds comment to ticket. **Request:** ```json { - "ticket_id": "123456789", + "ticket_id": 123, "comment_text": "Comment content", - "markdown_enabled": true, // Optional, default false - "user_name": "User" // Optional, default "User" + "markdown_enabled": true } ``` @@ -167,522 +365,363 @@ Adds a comment to a ticket. ```json { "success": true, - "user_name": "User", - "created_at": "Jan 01, 2026 12:00", - "markdown_enabled": 1, - "comment_text": "Comment content" + "user_name": "Jared Vititoe", + "created_at": "Jan 01, 2026 12:00" } ``` -### POST `/create_ticket_api.php` -**EXTERNAL API** used by hwmonDaemon for automated ticket creation. +## Key Features Implementation -**Request:** -```json -{ - "title": "[hostname][auto][hardware]Issue[single-node][production][maintenance]", - "description": "Detailed hardware issue...", - "priority": "2", - "category": "Hardware", - "type": "Problem" -} +### Feature 1: Activity Timeline +**Location**: Ticket view → Activity tab + +**Implementation**: +- `AuditLogModel->getTicketTimeline()` - Fetches all events for a ticket +- Shows: creates, updates, comments, assignments, status changes +- Displays: user, action, timestamp, details +- CSS: timeline-content boxes with icons +- Dark mode: Fully supported + +**Code**: `views/TicketView.php:258-282`, `models/AuditLogModel.php:getTicketTimeline()` + +### Feature 2: Ticket Assignment +**Location**: Ticket view → "Assigned to" dropdown, Dashboard → "Assigned To" column + +**Implementation**: +- Database: `tickets.assigned_to` column +- Models: `TicketModel->assignTicket()`, `TicketModel->unassignTicket()` +- API: `api/assign_ticket.php` +- Dashboard: Shows assigned user in table +- Auto-saves on change +- Audit logged + +**Code**: `views/TicketView.php:170-181`, `assets/js/ticket.js:handleAssignmentChange()` + +### Feature 3: Status Transitions with Workflows +**Location**: Ticket view → Status dropdown (header) + +**Implementation**: +- Database: `status_transitions` table defines allowed transitions +- Models: `WorkflowModel->isTransitionAllowed()`, `WorkflowModel->getAllowedTransitions()` +- Dropdown shows only valid transitions for current status +- Server-side validation prevents invalid changes +- Can require comments or admin privileges +- Removed from hamburger menu (was duplicate) + +**Code**: `models/WorkflowModel.php`, `api/update_ticket.php:130-144`, `views/TicketView.php:185-198` + +### Feature 4: Ticket Templates +**Location**: Create ticket page → Template selector + +**Implementation**: +- Database: `ticket_templates` table +- Models: `TemplateModel->getAllTemplates()`, `TemplateModel->getTemplateById()` +- API: `api/get_template.php` +- JavaScript: `loadTemplate()` in dashboard.js +- Auto-fills: title, description, category, type, priority +- 4 default templates included + +**Code**: `views/CreateTicketView.php:27-39`, `assets/js/dashboard.js:loadTemplate()` + +### Feature 5: Bulk Actions (Admin Only) +**Location**: Dashboard → Checkboxes + Toolbar (admins only) + +**Implementation**: +- Database: `bulk_operations` table tracks operations +- Models: `BulkOperationsModel->processBulkOperation()` +- API: `api/bulk_operation.php` +- UI: Toolbar appears when tickets selected +- Operations: Bulk close, bulk assign, bulk priority +- All operations audit logged +- Server-side admin validation + +**Code**: `views/DashboardView.php:176-188`, `assets/js/dashboard.js:bulkClose()`, `models/BulkOperationsModel.php` + +## Authentication & SSO Integration + +### Authelia Integration +User information passed via HTTP headers: +- `Remote-User`: Username +- `Remote-Name`: Display name +- `Remote-Email`: Email +- `Remote-Groups`: Comma-separated groups + +### Session Management +```php +$_SESSION['user'] = [ + 'user_id' => 123, + 'username' => 'jared', + 'display_name' => 'Jared Vititoe', + 'email' => 'jared@lotusguild.org', + 'is_admin' => true // true if 'admins' in Remote-Groups +]; ``` -**Response:** -```json -{ - "success": true, - "ticket_id": "123456789", - "message": "Ticket created successfully" -} -``` -**OR** (if duplicate): -```json -{ - "success": false, - "error": "Duplicate ticket", - "existing_ticket_id": "987654321" -} -``` +### Admin Privileges +- Bulk operations (close, assign, priority) +- Future: Admin-only transitions -**Special Features:** -- Duplicate detection via SHA-256 hashing -- Hash based on: hostname, SMART attributes, environment tags, device -- 24-hour duplicate window -- Sends Discord webhook notification -- Auto-creates tickets table if not exists +## Frontend Components (Updated) -## Frontend Components +### Dashboard (`DashboardView.php` + `dashboard.js`) -### Dashboard (`views/DashboardView.php` + `assets/js/dashboard.js`) - -**Features:** -- Pagination (default 15, configurable via settings) +**Features**: +- Sortable columns including new "Assigned To" column - Search (title, description, ticket_id, category, type) -- Status filtering (Open, In Progress, Closed) -- Category/Type filtering via hamburger menu -- Column sorting (click headers) -- Theme toggle (light/dark, persisted to localStorage) -- Settings modal (rows per page) +- Status filtering (default: Open + In Progress) +- Pagination (configurable) +- Dark mode toggle +- **Bulk Actions Toolbar** (admin only): + - Checkboxes on each ticket + - "Select All" checkbox + - Bulk close, assign, priority buttons + - Shows count of selected tickets -**Default Behavior:** -- Shows Open + In Progress tickets (Closed hidden) -- Use `?show_all=1` to see all tickets -- Use `?status=Open,Closed` for specific statuses +**Hamburger Menu**: +- Category/Type filtering +- Apply/Clear filters +- No status field (removed) -**Hamburger Menu:** -- Left sidebar with filters -- Multi-select checkboxes -- Apply/Clear filter buttons +### Ticket View (`TicketView.php` + `ticket.js`) -### Ticket View (`views/TicketView.php` + `assets/js/ticket.js`) +**Features**: +- **Tabbed Interface**: Description, Comments, Activity +- **Activity Timeline**: Complete audit trail with icons +- **Assignment Dropdown**: Assign to users +- **Status Dropdown**: Workflow-validated status changes (header) +- **Hamburger Menu**: Priority, Category, Type editing +- **Edit Button**: Title and description editing +- **Markdown Comments**: With live preview +- **Dark Mode**: Comprehensive support -**Features:** -- Tabbed interface (Description, Comments) -- Inline editing via Edit button -- Real-time status/priority indicators -- Markdown support for comments -- Live markdown preview toggle +**Visual Indicators**: +- Priority colors (P1=Red, P2=Orange, P3=Blue, P4=Green, P5=Gray) +- Status badges (Open=Green, In Progress=Yellow, Closed=Red, Resolved=Green) +- Priority border colors on ticket container -**Hamburger Menu (Ticket Page):** -- Quick edit: Status, Priority, Category, Type -- Click value → dropdown → save/cancel -- Updates main page elements dynamically -- Changes ticket border color based on priority +### Create Ticket (`CreateTicketView.php`) -**Visual Indicators:** +**Features**: +- **Template Selector**: Quick-fill from templates +- Standard fields: title, description, status, priority, category, type +- Form validation +- Discord webhook on creation -Priority Colors: -- P1 (Critical): Red `#ff4d4d` -- P2 (High): Orange `#ffa726` -- P3 (Medium): Blue `#42a5f5` -- P4 (Low): Green `#66bb6a` -- P5 (Lowest): Gray `#9e9e9e` +## Dark Mode (Fixed) -Status Colors: -- Open: Green `#28a745` -- In Progress: Yellow `#ffc107` -- Closed: Red `#dc3545` +### Comprehensive Dark Mode CSS +**Files**: `assets/css/ticket.css`, `assets/css/dashboard.css` -### Create Ticket (`views/CreateTicketView.php`) +**Colors**: +```css +body.dark-mode { + --bg-primary: #1a202c; /* Main background */ + --bg-secondary: #2d3748; /* Cards, inputs */ + --bg-tertiary: #4a5568; /* Hover states */ + --text-primary: #e2e8f0; /* Main text */ + --text-secondary: #cbd5e0; /* Secondary text */ + --text-muted: #a0aec0; /* Muted text */ + --border-color: #4a5568; /* Borders */ +} +``` -**Form Fields:** -- Title (required) -- Description (required, textarea) -- Status (dropdown, default: Open) -- Priority (dropdown, default: P4) -- Category (dropdown, default: General) -- Type (dropdown, default: Issue) +**Fixed Elements**: +- Timeline boxes (background + text) +- Bulk actions toolbar +- Tables and table rows +- Input fields and textareas +- Dropdowns and selects +- Comment boxes +- Modal dialogs +- All text elements -**On Submit:** -- Server-side validation -- Discord webhook notification -- Redirect to new ticket +**Important**: Used `!important` flags to override any conflicting styles. ## Configuration ### Environment Variables (`.env`) ```ini -DB_HOST= -DB_USER= -DB_PASS= +DB_HOST=10.10.10.50 +DB_USER=tinkertickets +DB_PASS=password DB_NAME=ticketing_system DISCORD_WEBHOOK_URL=https://discord.com/api/webhooks/... ``` -**CRITICAL:** `.env` is gitignored! Never commit this file. +**CRITICAL**: `.env` is gitignored! Never commit this file. -### Config (`config/config.php`) -```php -$GLOBALS['config'] = [ - 'DB_HOST' => $envVars['DB_HOST'], - 'DB_USER' => $envVars['DB_USER'], - 'DB_PASS' => $envVars['DB_PASS'], - 'DB_NAME' => $envVars['DB_NAME'], - 'BASE_URL' => '', // Empty (serving from root) - 'ASSETS_URL' => '/assets', - 'API_URL' => '/api' -]; +### Apache Configuration +**Virtual Host**: Apache serving from `/root/code/tinker_tickets` + +```apache + + ServerName t.lotusguild.org + DocumentRoot /root/code/tinker_tickets + + + Options -Indexes +FollowSymLinks + AllowOverride All + Require all granted + + RewriteEngine On + RewriteBase / + RewriteRule ^ticket/([0-9]+)$ ticket.php?id=$1 [L,QSA] + RewriteRule ^ticket/create$ ticket.php?action=create [L,QSA] + + ``` -## Deployment System +## Deployment -### Auto-Deploy Pipeline +### Git Auto-Deploy +**Repository**: https://code.lotusguild.org/LotusGuild/tinker_tickets -**Gitea → Webhook → Production Server** +**Flow**: +1. Push to `main` branch +2. Auto-deploys to `/root/code/tinker_tickets` on 10.10.10.45 +3. `.env` is preserved +4. Migrations must be run manually -1. **Push to `main` branch** on Gitea (code.lotusguild.org) -2. **Gitea sends webhook** to `http://10.10.10.45:9000/hooks/tinker-deploy` -3. **Webhook service** validates signature and triggers deploy script -4. **Deploy script** pulls code, preserves `.env`, sets permissions - -### Webhook Configuration - -**Service:** `/etc/systemd/system/webhook.service` -```ini -[Unit] -Description=Webhook Listener for Auto Deploy -After=network.target - -[Service] -ExecStart=/usr/bin/webhook -hooks /etc/webhook/hooks.json -port 9000 -Restart=always -User=root -``` - -**Hooks:** `/etc/webhook/hooks.json` -```json -{ - "id": "tinker-deploy", - "execute-command": "/usr/local/bin/tinker_deploy.sh", - "command-working-directory": "/var/www/html/tinkertickets", - "response-message": "Deploying tinker_tickets...", - "trigger-rule": { - "match": { - "type": "payload-hash-sha256", - "secret": "...", - "parameter": { - "source": "header", - "name": "X-Gitea-Signature" - } - } - } -} -``` - -**Deploy Script:** `/usr/local/bin/tinker_deploy.sh` +### Running Migrations ```bash -#!/bin/bash -set -e -WEBROOT="/var/www/html/tinkertickets" - -# Backup .env -if [ -f "$WEBROOT/.env" ]; then - cp "$WEBROOT/.env" /tmp/.env.backup -fi - -# Pull latest code -if [ ! -d "$WEBROOT/.git" ]; then - rm -rf "$WEBROOT" - git clone https://code.lotusguild.org/LotusGuild/tinker_tickets.git "$WEBROOT" -else - cd "$WEBROOT" - git fetch --all - git reset --hard origin/main -fi - -# Restore .env -if [ -f /tmp/.env.backup ]; then - mv /tmp/.env.backup "$WEBROOT/.env" -fi - -# Set permissions -chown -R www-data:www-data "$WEBROOT" +cd /root/code/tinker_tickets/migrations +mysql -h 10.10.10.50 -u tinkertickets -p'pass' ticketing_system < 007_add_ticket_assignment.sql +mysql -h 10.10.10.50 -u tinkertickets -p'pass' ticketing_system < 008_add_status_workflows.sql +mysql -h 10.10.10.50 -u tinkertickets -p'pass' ticketing_system < 009_add_ticket_templates.sql +mysql -h 10.10.10.50 -u tinkertickets -p'pass' ticketing_system < 010_add_bulk_operations.sql +mysql -h 10.10.10.50 -u tinkertickets -p'pass' ticketing_system < 011_remove_view_tracking.sql ``` -**IMPORTANT NOTES:** -- **Test thoroughly before pushing to main!** -- Low traffic (single user), so testing in production is acceptable -- But avoid breaking changes -- `.env` is preserved across deployments -- Database changes require manual migration - -### Nginx Configuration - -**Site Config:** `/etc/nginx/sites-enabled/tinker_prod` -```nginx -server { - listen 80; - server_name t.lotusguild.org; - root /var/www/html/tinkertickets; - index index.php index.html; - - location / { - try_files $uri $uri/ /index.php?$query_string; - } - - location ~ \.php$ { - include snippets/fastcgi-php.conf; - fastcgi_pass unix:/var/run/php/php-fpm.sock; - } - - location ~ /\.env { - deny all; - } -} -``` - -**Key Points:** -- Clean URLs via `try_files` -- PHP-FPM via Unix socket -- `.env` explicitly denied - -## Hardware Monitoring Integration - -### hwmonDaemon Overview - -The `hwmonDaemon` runs on all Proxmox VE servers as a systemd timer (hourly). It monitors: -- SMART drive health -- Disk usage -- Memory (including ECC errors) -- CPU usage -- Network connectivity (Management + Ceph networks) -- System logs for drive errors - -**When issues are detected**, it automatically creates tickets via `/create_ticket_api.php`. - -### Daemon Configuration - -**Service:** `/etc/systemd/system/hwmon.service` -- Executes Python script from Gitea URL (self-updating) -- Runs as root for hardware access -- Auto-restarts on failure - -**Timer:** `/etc/systemd/system/hwmon.timer` -- Runs hourly -- 5-minute randomized delay - -**API Endpoint:** -```python -TICKET_API_URL = 'http://10.10.10.45/create_ticket_api.php' -``` - -### Ticket Title Format - -hwmonDaemon creates tickets with structured titles: -``` -[hostname][auto][hardware]Issue Description[single-node][production][maintenance] -``` - -**Components:** -- `[hostname]`: Server name -- `[auto]`: Automated creation -- `[hardware]`: Issue category -- Issue Description: e.g., "Drive /dev/sda has SMART issues: Reallocated_Sector_Ct" -- `[single-node]`: Scope -- `[production]`: Environment -- `[maintenance]`: Ticket type - -### Duplicate Detection - -Tickets are hashed based on: -- Hostname -- SMART attribute types (not values) -- Environment tags -- Device path (for drive issues) - -**Hash Window:** 24 hours - -This prevents duplicate tickets for the same issue on the same host. - ## Development Guidelines ### Code Style -- Tabs for indentation in PHP -- Parameterized queries (prepared statements) -- Output escaping with `htmlspecialchars()` -- Error logging to `/tmp/api_debug.log` - -### Security Practices -- **SQL Injection**: All queries use prepared statements -- **XSS**: HTML output escaped -- **CSRF**: Not implemented (single-user system) -- **Environment Variables**: `.env` gitignored -- **File Permissions**: `www-data:www-data` ownership +- **PHP**: Tabs for indentation, prepared statements, `htmlspecialchars()` for output +- **JavaScript**: Vanilla JS, `fetch()` for AJAX, clear function names +- **CSS**: CSS variables for theming, mobile-responsive +- **Security**: No SQL injection, XSS prevention, session validation ### Error Handling -- API endpoints use output buffering -- Errors returned as JSON with `success: false` -- Debug logging in `/tmp/api_debug.log` -- Display errors disabled in production +- APIs return JSON with `{success: bool, error: string}` +- Debug logging to `/tmp/api_debug.log` (update_ticket.php) +- User-friendly error messages -### JavaScript Patterns -- Vanilla JavaScript (no framework) -- `DOMContentLoaded` for initialization -- `fetch()` for AJAX -- `window.ticketData` for ticket pages -- CSS class toggling for state changes +### Adding New Features +1. **Database**: Create migration in `migrations/` +2. **Model**: Add methods to relevant Model class +3. **API**: Create API endpoint in `api/` (with auth check) +4. **Controller**: Update controller to load data +5. **View**: Add UI elements +6. **JavaScript**: Add interactivity +7. **CSS**: Style for light + dark mode +8. **Test**: Test thoroughly before pushing -## Common Tasks +## ANSI Art Redesign (Next Priority) -### Adding a New Ticket Field +### Goal +Transform Tinker Tickets into a retro terminal aesthetic using ANSI art and ASCII characters. -1. **Database:** Add column to `tickets` table on MariaDB server -2. **Model:** Update `TicketModel.php`: - - `getTicketById()` - - `updateTicket()` - - `createTicket()` -3. **API:** Update `update_ticket.php`: - - Add to validation - - Add to merge logic (line 73-81) -4. **Views:** - - Add field to `TicketView.php` - - Add field to `CreateTicketView.php` -5. **JavaScript:** Add to hamburger menu in `dashboard.js` (if editable) -6. **CSS:** Add styling if needed +### Design Concept +- **Terminal-style borders**: Use box-drawing characters (┌─┐│└─┘) +- **Monospace fonts**: Courier New, Consolas, Monaco +- **ASCII art headers**: Stylized "TINKER TICKETS" banner +- **Retro color palette**: Green terminal, amber terminal, or custom +- **Template objects**: Reusable border/box components -### Modifying Status/Priority Values +### Implementation Approach +1. **CSS Variables**: Define ANSI color palette +2. **Border Components**: Create CSS classes for boxes with ASCII borders +3. **Typography**: Monospace fonts throughout +4. **Icons**: Replace emoji with ASCII art +5. **Dashboard**: Terminal-style table with borders +6. **Tickets**: Box-drawing characters for sections +7. **Forms**: Terminal-style input boxes -1. **API:** Update validation in `update_ticket.php`:172 - - Status: Line 102-108 - - Priority: Line 93-98 -2. **Views:** Update dropdowns: - - `TicketView.php:410-414` (status) - - `TicketView.php:426-432` (priority) - - `CreateTicketView.php` -3. **JavaScript:** Update hamburger options in `dashboard.js` -4. **CSS:** Add color classes to `dashboard.css` and `ticket.css` +### Reference Colors (Classic Terminal) +```css +:root { + --ansi-black: #000000; + --ansi-green: #00ff00; + --ansi-amber: #ffb000; + --ansi-blue: #0000ff; + --ansi-cyan: #00ffff; + --ansi-white: #ffffff; + --ansi-bg: #000000; +} +``` -### Changing Discord Notifications - -Edit `update_ticket.php` → `sendDiscordWebhook()` (lines 135-219): -- Change embed structure -- Modify color mapping -- Add/remove fields -- Update ticket URL - -Also check `TicketController.php` → `sendDiscordWebhook()` (lines 128-207) for ticket creation webhooks. - -### Updating Pagination Defaults - -1. **Controller:** `DashboardController.php:16` (default: 15) -2. **JavaScript:** `dashboard.js:128-133` (settings modal options) -3. **Cookie:** Stored as `ticketsPerPage` - -## Known Behaviors & Quirks - -### Ticket ID Generation -- Format: 9-digit random number with leading zeros -- Generation: `sprintf('%09d', mt_rand(1, 999999999))` -- Stored as VARCHAR -- **Collision possible** (no uniqueness check beyond DB constraint) - -### Status Filtering -- **Default:** Shows Open + In Progress (hides Closed) -- `?show_all=1` → All statuses -- `?status=Open,Closed` → Specific statuses -- No status param → Default behavior - -### Markdown Rendering -- Client-side only (marked.js from CDN) -- Toggle must be enabled before preview works -- **XSS Risk:** Consider adding DOMPurify - -### CSS Class Naming -- Status: `status-Open`, `status-In-Progress`, `status-Closed` -- Spaces replaced with hyphens -- Priority: `priority-1` through `priority-5` - -### Theme Persistence -- Stored: `localStorage['theme']` → `light` or `dark` -- Applied via `data-theme` attribute on `` -- CSS variables change based on theme +### Example Box Template +``` +┌─────────────────────────────┐ +│ TICKET #123 │ +├─────────────────────────────┤ +│ Title: Hardware Failure │ +│ Status: [OPEN] │ +│ Priority: P1 (CRITICAL) │ +└─────────────────────────────┘ +``` ## Debugging -### API Issues +### Common Issues ```bash +# API debug logs tail -f /tmp/api_debug.log + +# Database connection +mysql -h 10.10.10.50 -u tinkertickets -p ticketing_system + +# JavaScript console +# Open browser DevTools (F12) → Console tab + +# Check dark mode +# localStorage.getItem('theme') ``` -### JavaScript Issues -- Browser console (F12) -- Check Network tab for API responses -- Look for `console.log()` statements - -### Database Issues -```bash -# Connect to MariaDB server -ssh root@ -mysql ticketing_system -``` - -### Deployment Issues -```bash -# On production server (10.10.10.45) -journalctl -u webhook.service -f -systemctl status webhook.service - -# Manual deploy -cd /var/www/html/tinkertickets -git pull -chown -R www-data:www-data . -``` - -### hwmonDaemon Issues -```bash -# On Proxmox server -journalctl -u hwmon.service -f -systemctl status hwmon.timer - -# Manual test -python3 /path/to/hwmonDaemon.py --dry-run -``` +### Known Behaviors +- Ticket viewing no longer tracked (011 migration removes view logs) +- Status can only be changed via header dropdown (removed from hamburger) +- Bulk actions only visible to admins +- Templates are optional when creating tickets +- Workflow validation prevents invalid status transitions ## Important Notes for AI Assistants -1. **Always read existing code** before suggesting changes -2. **Test carefully** - auto-deploy to production is enabled -3. **Database changes** require manual migration (no auto-rollback) -4. **Preserve security** (prepared statements, escaping, `.env` protection) -5. **Consider auto-deploy** when making changes -6. **Single-user system** - authentication/authorization not implemented -7. **hwmonDaemon integration** - test with `create_ticket_api.php` -8. **Duplicate detection** - understand hashing for automated tickets -9. **Discord webhooks** - changes trigger notifications -10. **MariaDB on separate server** - can't access directly from this machine - -## Future Considerations - -### Potential Improvements -- User authentication/authorization -- CSRF protection -- File attachments -- Email notifications -- Advanced search/filters -- Ticket assignment -- Activity/audit log -- API rate limiting -- Database migrations system -- Unit tests -- DOMPurify for Markdown XSS protection - -### Performance Optimizations -- Database indexes -- Query caching -- Lazy load comments -- Minify/bundle assets - -## Related Systems - -### React Beta Site -- **URL:** https://beta.t.lotusguild.org -- **Branch:** `react_test` -- **Status:** Early development (brother's project) -- **Deploy:** Separate webhook + script (`tinker_react_deploy.sh`) -- **Location:** `/var/www/html/tinkertickets-react` +1. **All 5 features are complete and deployed** +2. **Dark mode is fixed** with comprehensive CSS +3. **Next priority is ANSI Art redesign** (major visual overhaul) +4. **Database at 10.10.10.50**, can't access directly from dev machine +5. **Auto-deploy is active**, test carefully before pushing +6. **Session format**: `$_SESSION['user']['user_id']` (not `$_SESSION['user_id']`) +7. **API auth**: Check `$_SESSION['user']['user_id']` exists +8. **Admin check**: `$_SESSION['user']['is_admin'] ?? false` +9. **Config path**: `config/config.php` (not `config/db.php`) +10. **Migrations**: Must be run manually on database server ## File Reference Quick Guide | File | Purpose | Key Functions | |------|---------|---------------| -| `index.php` | Router | URL routing, DB connection | -| `create_ticket_api.php` | hwmonDaemon API | Duplicate detection, auto-tickets | -| `api/update_ticket.php` | Update API | Partial updates, Discord webhooks | -| `api/add_comment.php` | Comment API | Markdown-enabled comments | -| `models/TicketModel.php` | Ticket data layer | CRUD, filtering, sorting | -| `models/CommentModel.php` | Comment data layer | Get/add comments | -| `controllers/DashboardController.php` | Dashboard logic | Pagination, filters | -| `controllers/TicketController.php` | Ticket logic | CRUD, webhooks | -| `assets/js/dashboard.js` | Dashboard UI | Filters, sorting, hamburger | -| `assets/js/ticket.js` | Ticket UI | Edit mode, comments, markdown | -| `assets/css/dashboard.css` | Shared styles | Layout, table, theme | -| `assets/css/ticket.css` | Ticket styles | Ticket-specific components | +| `index.php` | Dashboard router | Database connection, routing | +| `ticket.php` | Ticket router | View/create ticket routing | +| `api/update_ticket.php` | Update API | Workflow validation, partial updates | +| `api/assign_ticket.php` | Assignment API | Assign/unassign tickets | +| `api/bulk_operation.php` | Bulk ops API | Admin bulk operations | +| `api/get_template.php` | Template API | Fetch ticket templates | +| `api/get_users.php` | Users API | Get user list | +| `models/TicketModel.php` | Ticket data | CRUD, assignment, filtering | +| `models/WorkflowModel.php` | Workflow rules | Status transition validation | +| `models/AuditLogModel.php` | Audit logging | Timeline, activity tracking | +| `models/TemplateModel.php` | Templates | Template CRUD | +| `models/BulkOperationsModel.php` | Bulk ops | Process bulk operations | +| `controllers/DashboardController.php` | Dashboard logic | Pagination, filters, assigned column | +| `controllers/TicketController.php` | Ticket logic | CRUD, timeline, templates | +| `assets/js/dashboard.js` | Dashboard UI | Filters, bulk actions, templates | +| `assets/js/ticket.js` | Ticket UI | Status updates, assignment, comments | +| `assets/css/dashboard.css` | Dashboard styles | Layout, table, bulk toolbar, dark mode | +| `assets/css/ticket.css` | Ticket styles | Timeline, ticket view, dark mode | -## Contact & Repository +## Repository & Contact -- **Gitea:** https://code.lotusguild.org/LotusGuild/tinker_tickets -- **Production:** https://t.lotusguild.org -- **Beta:** https://beta.t.lotusguild.org - -This is a personal project for infrastructure management. For issues, use the Gitea repository. +- **Gitea**: https://code.lotusguild.org/LotusGuild/tinker_tickets +- **Production**: http://t.lotusguild.org +- **Infrastructure**: LotusGuild data center management diff --git a/README.md b/README.md index 617c108..fb466e5 100644 --- a/README.md +++ b/README.md @@ -1,37 +1,274 @@ # Tinker Tickets -A lightweight PHP-based ticketing system designed for tracking and managing data center infrastructure issues. +A feature-rich PHP-based ticketing system designed for tracking and managing data center infrastructure issues with enterprise-grade workflow management. -## Features +## ✨ Core Features -- 📊 Clean dashboard interface with sortable columns -- 🎫 Customizable ticket creation and management -- 🔄 Real-time status updates and priority tracking -- 💬 Markdown-supported commenting system -- 🔔 Discord webhook integration for notifications +### 📊 Dashboard & Ticket Management +- **Smart Dashboard**: Sortable columns, advanced filtering by status/priority/category/type +- **Full-Text Search**: Search across tickets, descriptions, and metadata +- **Ticket Assignment**: Assign tickets to specific users with "Assigned To" column +- **Priority Tracking**: P1 (Critical) to P5 (Minimal Impact) with color-coded indicators +- **Custom Categories**: Hardware, Software, Network, Security, General +- **Ticket Types**: Maintenance, Install, Task, Upgrade, Issue, Problem -## Core Components +### 🔄 Workflow Management +- **Status Transitions**: Enforced workflow rules (Open → In Progress → Resolved → Closed) +- **Workflow Validation**: Server-side validation prevents invalid status changes +- **Admin Controls**: Certain transitions can require admin privileges +- **Comment Requirements**: Optional comment requirements for specific transitions +- **Activity Timeline**: Complete audit trail of all ticket changes -- **Dashboard**: View and filter tickets by status, priority, and type -- **Ticket Management**: Create, edit, and update ticket details -- **Priority Levels**: P1 (Critical) to P5 (Lowest) impact tracking -- **Categories**: Hardware, Software, Network, Security tracking -- **Comment System**: Markdown support for detailed documentation +### 💬 Collaboration Features +- **Markdown Comments**: Full Markdown support with live preview +- **User Tracking**: Tracks who created, updated, and assigned tickets +- **Activity Timeline**: Shows all ticket events (creates, updates, assignments, comments) +- **Real-time Updates**: AJAX-powered updates without page refreshes -## Technical Details +### 🎫 Ticket Templates +- **Quick Creation**: Pre-configured templates for common issues +- **Default Templates**: Hardware Failure, Software Installation, Network Issue, Maintenance +- **Auto-fill**: Templates populate title, description, category, type, and priority -- Backend: PHP with MariaDB database -- Frontend: HTML5, CSS3, JavaScript -- Authentication: Environment-based configuration -- API: RESTful endpoints for ticket operations +### 👥 User Management & Authentication +- **SSO Integration**: Authelia authentication with LLDAP backend +- **Role-Based Access**: Admin and standard user roles +- **User Display Names**: Support for display names and usernames +- **Session Management**: Secure PHP session handling -## Configuration +### ⚡ Bulk Actions (Admin Only) +- **Bulk Close**: Close multiple tickets at once +- **Bulk Assign**: Assign multiple tickets to a user +- **Bulk Priority**: Change priority for multiple tickets +- **Operation Tracking**: All bulk operations logged in audit trail -1. Create `.env` file with database credentials: +### 🔔 Notifications +- **Discord Integration**: Webhook notifications for ticket creation and updates +- **Rich Embeds**: Color-coded priority indicators and ticket links +- **Change Tracking**: Detailed notification of what changed + +### 🎨 User Interface +- **Dark Mode**: Full dark mode support with proper contrast +- **Responsive Design**: Works on desktop and mobile devices +- **Clean Layout**: Modern, intuitive interface +- **Hamburger Menu**: Quick access to ticket actions (priority, category, type) + +## 🏗️ Technical Architecture + +### Backend +- **Language**: PHP 7.4+ +- **Database**: MariaDB/MySQL +- **Architecture**: MVC pattern with models, views, controllers +- **ORM**: Custom database abstraction layer + +### Frontend +- **HTML5/CSS3**: Semantic markup with modern CSS +- **JavaScript**: Vanilla JS with Fetch API for AJAX +- **Markdown**: marked.js for Markdown rendering +- **Icons**: Unicode emoji icons + +### Database Schema +- **tickets**: Core ticket data with user tracking +- **comments**: Markdown-supported comments +- **users**: User accounts synced from LLDAP +- **audit_log**: Complete audit trail with JSON details +- **status_transitions**: Workflow configuration +- **ticket_templates**: Reusable ticket templates +- **bulk_operations**: Tracking for bulk admin operations + +### API Endpoints +- `/api/update_ticket.php` - Update ticket with workflow validation +- `/api/assign_ticket.php` - Assign ticket to user +- `/api/add_comment.php` - Add comment to ticket +- `/api/get_template.php` - Fetch ticket template +- `/api/get_users.php` - Get user list for assignments +- `/api/bulk_operation.php` - Perform bulk operations (admin only) + +## 🚀 Setup & Configuration + +### 1. Environment Configuration + +Create `.env` file in project root: ```env -DB_HOST=localhost -DB_USER=username -DB_PASS=password -DB_NAME=database -DISCORD_WEBHOOK_URL=your_webhook_url -``` \ No newline at end of file +DB_HOST=10.10.10.50 +DB_USER=tinkertickets +DB_PASS=your_password +DB_NAME=ticketing_system +DISCORD_WEBHOOK_URL=https://discord.com/api/webhooks/... +``` + +### 2. Database Setup + +Run migrations in order: +```bash +# Navigate to project directory +cd /root/code/tinker_tickets + +# Run each migration +mysql -h 10.10.10.50 -u tinkertickets -p ticketing_system < migrations/001_initial_schema.sql +mysql -h 10.10.10.50 -u tinkertickets -p ticketing_system < migrations/007_add_ticket_assignment.sql +mysql -h 10.10.10.50 -u tinkertickets -p ticketing_system < migrations/008_add_status_workflows.sql +mysql -h 10.10.10.50 -u tinkertickets -p ticketing_system < migrations/009_add_ticket_templates.sql +mysql -h 10.10.10.50 -u tinkertickets -p ticketing_system < migrations/010_add_bulk_operations.sql +mysql -h 10.10.10.50 -u tinkertickets -p ticketing_system < migrations/011_remove_view_tracking.sql +``` + +### 3. Web Server Configuration + +**Apache Configuration** (recommended): +```apache + + ServerName t.lotusguild.org + DocumentRoot /root/code/tinker_tickets + + + Options -Indexes +FollowSymLinks + AllowOverride All + Require all granted + + # Enable mod_rewrite for clean URLs + RewriteEngine On + RewriteBase / + + # Route ticket URLs + RewriteRule ^ticket/([0-9]+)$ ticket.php?id=$1 [L,QSA] + + # Route ticket create + RewriteRule ^ticket/create$ ticket.php?action=create [L,QSA] + + +``` + +### 4. Authelia Integration + +Tinker Tickets uses Authelia for SSO. User information is passed via headers: +- `Remote-User`: Username +- `Remote-Name`: Display name +- `Remote-Email`: Email address +- `Remote-Groups`: User groups (comma-separated) + +Admin users must be in the `admins` group in LLDAP. + +## 📁 Project Structure + +``` +tinker_tickets/ +├── api/ # API endpoints +│ ├── add_comment.php +│ ├── assign_ticket.php +│ ├── bulk_operation.php +│ ├── get_template.php +│ ├── get_users.php +│ └── update_ticket.php +├── assets/ # Static assets +│ ├── css/ +│ │ ├── dashboard.css +│ │ └── ticket.css +│ └── js/ +│ ├── dashboard.js +│ └── ticket.js +├── config/ # Configuration +│ └── config.php +├── controllers/ # MVC Controllers +│ ├── DashboardController.php +│ └── TicketController.php +├── models/ # Data models +│ ├── AuditLogModel.php +│ ├── BulkOperationsModel.php +│ ├── CommentModel.php +│ ├── TemplateModel.php +│ ├── TicketModel.php +│ ├── UserModel.php +│ └── WorkflowModel.php +├── views/ # View templates +│ ├── CreateTicketView.php +│ ├── DashboardView.php +│ └── TicketView.php +├── migrations/ # Database migrations +│ ├── 001_initial_schema.sql +│ ├── 007_add_ticket_assignment.sql +│ ├── 008_add_status_workflows.sql +│ ├── 009_add_ticket_templates.sql +│ ├── 010_add_bulk_operations.sql +│ └── 011_remove_view_tracking.sql +├── index.php # Dashboard entry point +├── ticket.php # Ticket view/create entry point +└── .env # Environment configuration +``` + +## 🔐 Security Features + +- **SQL Injection Prevention**: All queries use prepared statements +- **XSS Protection**: All output is properly escaped with `htmlspecialchars()` +- **Session Security**: Secure PHP session handling +- **Admin Validation**: Server-side admin checks for privileged operations +- **Workflow Enforcement**: Status transitions validated server-side +- **Audit Logging**: Complete audit trail of all actions + +## 🎯 Workflow States + +### Default Workflow +``` +Open → In Progress → Resolved → Closed + ↓ ↓ ↓ + └─────────┴──────────┘ + (can reopen) +``` + +### Workflow Configuration +Status transitions are defined in the `status_transitions` table: +- `from_status`: Current status +- `to_status`: Target status +- `requires_comment`: Whether transition requires a comment +- `requires_admin`: Whether transition requires admin privileges +- `is_active`: Whether transition is enabled + +## 📝 Usage Examples + +### Creating a Ticket +1. Click "New Ticket" button +2. Select template (optional) - auto-fills common fields +3. Fill in title, description, category, type, priority +4. Click "Create Ticket" + +### Updating Ticket Status +1. Open ticket +2. Click status dropdown (next to priority badge) +3. Select allowed status (workflow-validated) +4. Confirm if comment is required + +### Assigning Tickets +1. Open ticket or use dashboard bulk actions +2. Select user from "Assigned to" dropdown +3. Changes are auto-saved + +### Bulk Operations (Admin Only) +1. Check multiple tickets on dashboard +2. Select bulk action (Close, Assign, Change Priority) +3. Complete operation +4. All actions are logged in audit trail + +## 🔮 Roadmap + +- ✅ Activity Timeline +- ✅ Ticket Assignment +- ✅ Status Transitions with Workflows +- ✅ Ticket Templates +- ✅ Bulk Actions (Admin Only) +- 🎨 **ANSI Art Redesign** (Next Priority) +- 🔗 Ticket Dependencies (blocks/blocked by) +- 📊 Custom Dashboard Widgets +- 🔧 Custom Fields per Category + +## 🤝 Contributing + +This is an internal tool for LotusGuild infrastructure management. For feature requests or bug reports, contact the infrastructure team. + +## 📄 License + +Internal use only - LotusGuild Infrastructure + +## 🙏 Credits + +Built with ❤️ for the LotusGuild community +Powered by PHP, MariaDB, and lots of coffee ☕ diff --git a/assets/css/dashboard.css b/assets/css/dashboard.css index 9466a26..2cbeac1 100644 --- a/assets/css/dashboard.css +++ b/assets/css/dashboard.css @@ -845,3 +845,59 @@ body.dark-mode .modal-body select { justify-content: center; } } + +/* Comprehensive Dark Mode Fix - Dashboard */ +body.dark-mode { + background: #1a202c !important; + color: #e2e8f0 !important; +} + +body.dark-mode .dashboard-container, +body.dark-mode .dashboard-content { + background: #1a202c !important; + color: #e2e8f0 !important; +} + +/* Ensure table has dark background */ +body.dark-mode table { + background: #2d3748 !important; +} + +body.dark-mode table thead { + background: #1a202c !important; +} + +body.dark-mode table tbody tr { + background: #2d3748 !important; +} + +body.dark-mode table tbody tr:hover { + background: #374151 !important; +} + +body.dark-mode table td, +body.dark-mode table th { + color: #e2e8f0 !important; + border-color: #4a5568 !important; +} + +/* Fix search box */ +body.dark-mode .search-box, +body.dark-mode input[type="search"], +body.dark-mode input[type="text"] { + background: #2d3748 !important; + color: #e2e8f0 !important; + border-color: #4a5568 !important; +} + +/* Fix any white backgrounds in modals */ +body.dark-mode .modal-content { + background: #2d3748 !important; + color: #e2e8f0 !important; +} + +/* Fix dropdown menus */ +body.dark-mode select option { + background: #2d3748 !important; + color: #e2e8f0 !important; +} diff --git a/assets/css/ticket.css b/assets/css/ticket.css index c436388..f2e180b 100644 --- a/assets/css/ticket.css +++ b/assets/css/ticket.css @@ -599,3 +599,80 @@ body.dark-mode #activity-tab { body.dark-mode #activity-tab p { color: var(--text-primary, #f7fafc); } + +/* Comprehensive Dark Mode Fix - Ensure no white on white */ +body.dark-mode { + --bg-primary: #1a202c; + --bg-secondary: #2d3748; + --bg-tertiary: #4a5568; + --text-primary: #e2e8f0; + --text-secondary: #cbd5e0; + --text-muted: #a0aec0; + --border-color: #4a5568; + --card-bg: #2d3748; +} + +/* Ensure ticket container has dark background */ +body.dark-mode .ticket-container { + background: #1a202c !important; + color: #e2e8f0 !important; +} + +/* Ensure all ticket details sections are dark */ +body.dark-mode .ticket-details { + background: #1a202c !important; + color: #e2e8f0 !important; +} + +/* Ensure detail groups are dark */ +body.dark-mode .detail-group { + background: transparent !important; + color: #e2e8f0 !important; +} + +/* Ensure labels are visible */ +body.dark-mode .detail-group label, +body.dark-mode label { + color: #cbd5e0 !important; +} + +/* Fix textarea and input fields */ +body.dark-mode textarea, +body.dark-mode input[type="text"] { + background: #2d3748 !important; + color: #e2e8f0 !important; + border-color: #4a5568 !important; +} + +/* Ensure timeline event backgrounds are dark */ +body.dark-mode .timeline-event { + background: transparent !important; +} + +/* Fix any remaining white text issues */ +body.dark-mode .timeline-details { + color: #cbd5e0 !important; + background: transparent !important; +} + +/* Fix comment sections */ +body.dark-mode .comment { + background: #2d3748 !important; + color: #e2e8f0 !important; +} + +body.dark-mode .comment-text { + color: #e2e8f0 !important; +} + +body.dark-mode .comment-header { + color: #cbd5e0 !important; +} + +/* Fix any form elements */ +body.dark-mode select, +body.dark-mode .editable { + background: #2d3748 !important; + color: #e2e8f0 !important; + border-color: #4a5568 !important; +}