import os import logging import uuid from datetime import datetime from flask import (Blueprint, render_template, redirect, url_for, flash, request, current_app, send_from_directory, abort) from flask_login import login_required, current_user from werkzeug.utils import secure_filename from app import db from app.models import (Ticket, Comment, Attachment, Notification, TicketStatus, TicketPriority, TicketCategory, User, UserRole, KnowledgeBase) from app.services.notification_service import ( notify_new_ticket, notify_status_change, notify_comment_added, notify_assignment, ) from app.services.log_service import log_action, log_ticket_history from app.services.validation_service import validate_file, render_comment_body tickets_bp = Blueprint('tickets', __name__) logger = logging.getLogger(__name__) # Allowed extensions for ticket and comment attachments. # validate_file() uses this set for both extension and magic-byte checks. ALLOWED_EXT = {'png', 'jpg', 'jpeg', 'gif', 'pdf', 'doc', 'docx', 'txt', 'zip', 'log'} def _strip_html(text: str) -> str: """Remove HTML tags from *text* for plain-text search matching. Comment bodies are stored as sanitized HTML (rendered at write time via render_comment_body). Searching with ilike('%term%') against raw HTML produces two problems: 1. A search for 'bold' misses 'bold' in the stored body. 2. HTML tag names ('strong', 'pre') can accidentally match search terms. Stripping tags before comparison gives consistent, tag-agnostic results. Uses a simple regex rather than a full HTML parser — sufficient for the sanitized subset of HTML that bleach allows in comment bodies. """ import re return re.sub(r'<[^>]+>', '', text) def _resolve_mime_type(att): """Return a reliable MIME type for an attachment. Browsers sometimes send 'application/octet-stream' for images on upload, and older attachments may have NULL mime_type. Fall back to an extension-based lookup so images are always served inline correctly. """ stored = (att.mime_type or '').lower().strip() if stored.startswith('image/'): return stored ext_map = { 'png': 'image/png', 'jpg': 'image/jpeg', 'jpeg': 'image/jpeg', 'gif': 'image/gif', 'webp': 'image/webp', 'svg': 'image/svg+xml', 'pdf': 'application/pdf', 'doc': 'application/msword', 'docx': 'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'txt': 'text/plain', 'log': 'text/plain', 'zip': 'application/zip', } ext = att.filename.rsplit('.', 1)[-1].lower() if '.' in att.filename else '' return ext_map.get(ext, stored or 'application/octet-stream') def save_attachment(file, ticket_id=None, comment_id=None, uploader_id=None): filename = secure_filename(file.filename) ext = filename.rsplit('.', 1)[1].lower() if '.' in filename else '' stored_name = f"{uuid.uuid4().hex}.{ext}" upload_dir = current_app.config['UPLOAD_FOLDER'] file.save(os.path.join(upload_dir, stored_name)) att = Attachment( ticket_id = ticket_id, comment_id = comment_id, filename = filename, stored_name= stored_name, file_size = os.path.getsize(os.path.join(upload_dir, stored_name)), mime_type = file.content_type, uploaded_by= uploader_id, ) db.session.add(att) return att filename = secure_filename(file.filename) ext = filename.rsplit('.', 1)[1].lower() if '.' in filename else '' stored_name = f"{uuid.uuid4().hex}.{ext}" upload_dir = current_app.config['UPLOAD_FOLDER'] file.save(os.path.join(upload_dir, stored_name)) att = Attachment( ticket_id = ticket_id, comment_id = comment_id, filename = filename, stored_name= stored_name, file_size = os.path.getsize(os.path.join(upload_dir, stored_name)), mime_type = file.content_type, uploaded_by= uploader_id, ) db.session.add(att) return att # ─── Dashboard ──────────────────────────────────────────────────────────────── @tickets_bp.route('/') @tickets_bp.route('/dashboard') @login_required def dashboard(): if current_user.is_it_staff: open_count = Ticket.query.filter_by(status=TicketStatus.OPEN).count() in_progress_count= Ticket.query.filter_by(status=TicketStatus.IN_PROGRESS).count() pending_count = Ticket.query.filter_by(status=TicketStatus.PENDING).count() resolved_count = Ticket.query.filter_by(status=TicketStatus.RESOLVED).count() my_tickets = Ticket.query.filter_by(assigned_to_id=current_user.id).filter( Ticket.status.notin_([TicketStatus.CLOSED]) ).order_by(Ticket.created_at.desc()).limit(10).all() recent_tickets = Ticket.query.order_by(Ticket.created_at.desc()).limit(15).all() return render_template('tickets/dashboard_it.html', open_count=open_count, in_progress_count=in_progress_count, pending_count=pending_count, resolved_count=resolved_count, my_tickets=my_tickets, recent_tickets=recent_tickets, ) else: my_tickets = Ticket.query.filter_by(created_by_id=current_user.id).order_by( Ticket.created_at.desc()).limit(20).all() open_count = sum(1 for t in my_tickets if t.status == TicketStatus.OPEN) active_count = sum(1 for t in my_tickets if t.status == TicketStatus.IN_PROGRESS) resolved_count = sum(1 for t in my_tickets if t.status == TicketStatus.RESOLVED) articles = KnowledgeBase.query.filter_by(is_published=True).order_by( KnowledgeBase.view_count.desc()).limit(5).all() return render_template('tickets/dashboard_employee.html', my_tickets=my_tickets, open_count=open_count, active_count=active_count, resolved_count=resolved_count, articles=articles, ) # ─── Create Ticket ──────────────────────────────────────────────────────────── @tickets_bp.route('/tickets/new', methods=['GET', 'POST']) @login_required def create_ticket(): if request.method == 'POST': title = request.form.get('title', '').strip() description = request.form.get('description', '').strip() category = request.form.get('category', TicketCategory.OTHER) priority = request.form.get('priority', TicketPriority.MEDIUM) location = request.form.get('location', '').strip() asset_tag = request.form.get('asset_tag', '').strip() if not title or not description: flash('Title and description are required.', 'danger') return render_template('tickets/create.html', categories=_categories(), priorities=_priorities()) ticket = Ticket( title = title, description = description, category = category, priority = priority, location = location, asset_tag = asset_tag, created_by_id = current_user.id, status = TicketStatus.OPEN, ) ticket.ticket_number = ticket.generate_ticket_number() db.session.add(ticket) db.session.flush() # get ticket.id before attachments # Handle file uploads for f in request.files.getlist('attachments'): if f and f.filename: file_error = validate_file(f, ALLOWED_EXT) if file_error: logger.warning(f'[TICKET UPLOAD REJECTED] {file_error} filename="{f.filename}" user_id={current_user.id}') continue save_attachment(f, ticket_id=ticket.id, uploader_id=current_user.id) log_action(current_user.id, 'ticket_create', 'ticket', ticket.id, f'ticket_number={ticket.ticket_number} priority={priority} category={category}') db.session.commit() logger.info(f'[TICKET CREATE] ticket_id={ticket.id} number={ticket.ticket_number} by user_id={current_user.id}') notify_new_ticket(ticket) flash(f'Ticket {ticket.ticket_number} created successfully!', 'success') return redirect(url_for('tickets.ticket_detail', ticket_id=ticket.id)) return render_template('tickets/create.html', categories=_categories(), priorities=_priorities()) # ─── Ticket List ────────────────────────────────────────────────────────────── @tickets_bp.route('/tickets') @login_required def ticket_list(): page = request.args.get('page', 1, type=int) status = request.args.get('status', '') priority = request.args.get('priority', '') category = request.args.get('category', '') search = request.args.get('q', '') query = Ticket.query if not current_user.is_it_staff: query = query.filter_by(created_by_id=current_user.id) if status: query = query.filter_by(status=status) if priority: query = query.filter_by(priority=priority) if category: query = query.filter_by(category=category) if search: # Extend search to cover comments and assignee name via outer joins. # distinct() prevents duplicate ticket rows when multiple comments match. # Comment bodies are stored as sanitized HTML — use REGEXP_REPLACE to # strip tags at the SQL level before matching so 'bold' finds # 'bold' and HTML tag names don't pollute results. from app.models import Comment from sqlalchemy import func assignee_alias = db.aliased(User) stripped_body = func.regexp_replace(Comment.body, r'<[^>]+>', '', 'g') query = ( query .outerjoin(Comment, Comment.ticket_id == Ticket.id) .outerjoin(assignee_alias, assignee_alias.id == Ticket.assigned_to_id) .filter( Ticket.title.ilike(f'%{search}%') | Ticket.ticket_number.ilike(f'%{search}%') | Ticket.description.ilike(f'%{search}%') | stripped_body.ilike(f'%{search}%') | assignee_alias.full_name.ilike(f'%{search}%') ) .distinct() ) tickets = query.order_by(Ticket.created_at.desc()).paginate(page=page, per_page=20) return render_template('tickets/list.html', tickets=tickets, status=status, priority=priority, category=category, search=search, statuses=_statuses(), priorities=_priorities(), categories=_categories(), ) # ─── Ticket Detail ──────────────────────────────────────────────────────────── @tickets_bp.route('/tickets/', methods=['GET', 'POST']) @login_required def ticket_detail(ticket_id): ticket = db.session.get(Ticket, ticket_id) or abort(404) # Employees can only view their own tickets if not current_user.is_it_staff and ticket.created_by_id != current_user.id: abort(403) if request.method == 'POST': body = request.form.get('body', '').strip() is_internal = bool(request.form.get('is_internal')) and current_user.is_it_staff if not body: flash('Comment cannot be empty.', 'danger') else: comment = Comment( ticket_id = ticket.id, author_id = current_user.id, body = render_comment_body(body), is_internal= is_internal, ) db.session.add(comment) db.session.flush() # ── Attachment limits (mirrors client-side constants in detail.html) MAX_COMMENT_FILES = 5 MAX_COMMENT_BYTES = 25 * 1024 * 1024 # 25 MB total per comment uploaded_files = [f for f in request.files.getlist('attachments') if f and f.filename] if len(uploaded_files) > MAX_COMMENT_FILES: db.session.rollback() logger.warning(f'[COMMENT UPLOAD REJECTED] Too many files ({len(uploaded_files)}) ticket_id={ticket.id} user_id={current_user.id}') flash(f'Too many attachments — maximum {MAX_COMMENT_FILES} files per comment.', 'danger') return redirect(url_for('tickets.ticket_detail', ticket_id=ticket.id)) total_bytes = 0 for f in uploaded_files: f.stream.seek(0, 2) total_bytes += f.stream.tell() f.stream.seek(0) if total_bytes > MAX_COMMENT_BYTES: db.session.rollback() logger.warning(f'[COMMENT UPLOAD REJECTED] Total size {total_bytes} exceeds limit ticket_id={ticket.id} user_id={current_user.id}') flash(f'Total attachment size exceeds the 25 MB limit per comment.', 'danger') return redirect(url_for('tickets.ticket_detail', ticket_id=ticket.id)) for f in uploaded_files: file_error = validate_file(f, ALLOWED_EXT) if file_error: logger.warning(f'[COMMENT UPLOAD REJECTED] {file_error} filename="{f.filename}" user_id={current_user.id}') continue save_attachment(f, ticket_id=ticket.id, comment_id=comment.id, uploader_id=current_user.id) log_action(current_user.id, 'comment_create', 'comment', comment.id, f'ticket_id={ticket.id} internal={is_internal}') db.session.commit() logger.info(f'[COMMENT CREATE] comment_id={comment.id} ticket_id={ticket.id} by user_id={current_user.id}') notify_comment_added(comment) flash('Comment added.', 'success') return redirect(url_for('tickets.ticket_detail', ticket_id=ticket.id)) comments = Comment.query.filter_by(ticket_id=ticket.id) if not current_user.is_it_staff: comments = comments.filter_by(is_internal=False) comments = comments.order_by(Comment.created_at.asc()).all() it_staff = User.query.filter( User.role.in_([UserRole.IT_STAFF, UserRole.ADMIN]), User.is_active == True, ).all() if current_user.is_it_staff else [] history = ticket.history.order_by('changed_at').all() return render_template('tickets/detail.html', ticket=ticket, comments=comments, it_staff=it_staff, history=history, statuses=_statuses(), priorities=_priorities(), ) # ─── Update Ticket (IT Only) ────────────────────────────────────────────────── @tickets_bp.route('/tickets//update', methods=['POST']) @login_required def update_ticket(ticket_id): if not current_user.is_it_staff: abort(403) ticket = db.session.get(Ticket, ticket_id) or abort(404) old_status = ticket.status old_priority = ticket.priority old_assigned = ticket.assigned_to_id new_status = request.form.get('status', ticket.status) new_priority = request.form.get('priority', ticket.priority) new_assigned = request.form.get('assigned_to_id', type=int) internal_notes= request.form.get('internal_notes', ticket.internal_notes) resolution = request.form.get('resolution_notes', ticket.resolution_notes) due_date_str = request.form.get('due_date', '') changes = [] if new_status != old_status: ticket.status = new_status log_ticket_history(ticket, 'status', old_status, new_status, current_user.id) changes.append(f'status: {old_status} → {new_status}') if new_status == TicketStatus.RESOLVED: ticket.resolved_at = datetime.utcnow() elif new_status == TicketStatus.CLOSED: ticket.closed_at = datetime.utcnow() if new_priority != old_priority: ticket.priority = new_priority log_ticket_history(ticket, 'priority', old_priority, new_priority, current_user.id) changes.append(f'priority: {old_priority} → {new_priority}') if new_assigned != old_assigned: # Resolve user IDs to full names for human-readable history entries. # None means unassigned. def _user_label(uid): if uid is None: return 'Unassigned' u = db.session.get(User, uid) return u.full_name if u else f'User #{uid}' ticket.assigned_to_id = new_assigned log_ticket_history(ticket, 'assigned_to', _user_label(old_assigned), _user_label(new_assigned), current_user.id) changes.append(f'assigned_to: {old_assigned} → {new_assigned}') # notify_assignment is called AFTER commit below — see Fix #13. ticket.internal_notes = internal_notes ticket.resolution_notes = resolution if due_date_str: try: ticket.due_date = datetime.strptime(due_date_str, '%Y-%m-%d') except ValueError: pass log_action(current_user.id, 'ticket_update', 'ticket', ticket.id, f'changes=[{"; ".join(changes)}]') db.session.commit() logger.info(f'[TICKET UPDATE] ticket_id={ticket.id} changes={changes} by user_id={current_user.id}') # Both notification calls are placed after commit so that create_notification's # independent commit never races against an uncommitted ticket state. If the # parent commit above had failed, neither notification would be sent — which # is the correct behaviour (no notification for a change that did not persist). if new_assigned != old_assigned: notify_assignment(ticket, current_user) if new_status != old_status: notify_status_change(ticket, old_status, current_user) flash('Ticket updated successfully.', 'success') return redirect(url_for('tickets.ticket_detail', ticket_id=ticket.id)) # ─── Delete Comment (IT Only) ───────────────────────────────────────────────── @tickets_bp.route('/comments//delete', methods=['POST']) @login_required def delete_comment(comment_id): comment = db.session.get(Comment, comment_id) or abort(404) ticket_id = comment.ticket_id # Authorization: IT staff may always delete any comment. # Employees may only delete their own comments, and only while the # ticket is still open or in-progress. Allowing deletion on resolved # or closed tickets would silently alter the historical record of a # completed support interaction. if not current_user.is_it_staff: if comment.author_id != current_user.id: abort(403) ticket = db.session.get(Ticket, ticket_id) or abort(404) if ticket.status in (TicketStatus.RESOLVED, TicketStatus.CLOSED): logger.warning( f'[COMMENT DELETE BLOCKED] comment_id={comment.id} ' f'ticket_id={ticket_id} status={ticket.status} ' f'user_id={current_user.id} — ticket is {ticket.status}' ) flash('Comments cannot be deleted on resolved or closed tickets.', 'warning') return redirect(url_for('tickets.ticket_detail', ticket_id=ticket_id)) # Include a truncated snapshot of the body in the audit log so the # content is recoverable from logs even after the DB row is gone. body_snapshot = comment.body[:200].replace('\n', ' ') log_action(current_user.id, 'comment_delete', 'comment', comment.id, f'ticket_id={ticket_id} body_snapshot="{body_snapshot}"') logger.info(f'[COMMENT DELETE] comment_id={comment.id} ticket_id={ticket_id} by user_id={current_user.id}') db.session.delete(comment) db.session.commit() flash('Comment deleted.', 'success') return redirect(url_for('tickets.ticket_detail', ticket_id=ticket_id)) # ─── Attachment Download ────────────────────────────────────────────────────── @tickets_bp.route('/attachments/') @login_required def download_attachment(att_id): att = db.session.get(Attachment, att_id) or abort(404) # Authorization: employees may only download attachments belonging to # their own tickets. IT staff have unrestricted access across all tickets. # att.ticket_id is the authoritative link — comment attachments also carry # the parent ticket_id, so this check covers both ticket and comment files. if not current_user.is_it_staff: ticket = db.session.get(Ticket, att.ticket_id) or abort(404) if ticket.created_by_id != current_user.id: logger.warning( f'[ATTACHMENT ACCESS DENIED] att_id={att_id} ticket_id={att.ticket_id} ' f'user_id={current_user.id}' ) abort(403) upload_dir = current_app.config['UPLOAD_FOLDER'] mime = _resolve_mime_type(att) is_image = mime.startswith('image/') return send_from_directory( upload_dir, att.stored_name, as_attachment = not is_image, download_name = att.filename, mimetype = mime, ) # ─── Notifications ──────────────────────────────────────────────────────────── @tickets_bp.route('/notifications') @login_required def notifications(): notifs = Notification.query.filter_by(user_id=current_user.id).order_by( Notification.created_at.desc()).paginate(page=request.args.get('page', 1, type=int), per_page=30) return render_template('tickets/notifications.html', notifs=notifs) @tickets_bp.route('/notifications/mark-read', methods=['POST']) @login_required def mark_notifications_read(): Notification.query.filter_by(user_id=current_user.id, is_read=False).update({'is_read': True}) db.session.commit() return redirect(request.referrer or url_for('tickets.notifications')) # ─── Knowledge Base ─────────────────────────────────────────────────────────── @tickets_bp.route('/kb') @login_required def knowledge_base(): q = request.args.get('q', '').strip() category = request.args.get('category', '') sort = request.args.get('sort', 'popular') # 'popular' | 'newest' query = KnowledgeBase.query.filter_by(is_published=True) if q: query = query.filter( KnowledgeBase.title.ilike(f'%{q}%') | KnowledgeBase.tags.ilike(f'%{q}%') ) if category: query = query.filter_by(category=category) if sort == 'newest': query = query.order_by(KnowledgeBase.updated_at.desc()) else: query = query.order_by(KnowledgeBase.view_count.desc()) articles = query.all() categories = sorted({a.category for a in KnowledgeBase.query.filter_by(is_published=True).with_entities(KnowledgeBase.category).distinct() if a.category}) return render_template('tickets/knowledge_base.html', articles = articles, categories = categories, q = q, sel_category = category, sort = sort, ) @tickets_bp.route('/kb/') @login_required def kb_article(article_id): article = db.session.get(KnowledgeBase, article_id) or abort(404) # Increment view_count atomically at the SQL level. A Python-level # read-modify-write (article.view_count += 1) is not safe under concurrent # requests: two simultaneous reads both see the same value and one # increment is silently lost. The SQL expression KnowledgeBase.view_count + 1 # delegates the addition to the database, which serialises it correctly. from sqlalchemy import update as sa_update db.session.execute( sa_update(KnowledgeBase) .where(KnowledgeBase.id == article_id) .values(view_count=KnowledgeBase.view_count + 1) ) db.session.commit() # Re-fetch so the template receives the post-increment value. db.session.refresh(article) return render_template('tickets/kb_article.html', article=article) # ─── Helpers ───────────────────────────────────────────────────────────────── def _statuses(): return [TicketStatus.OPEN, TicketStatus.IN_PROGRESS, TicketStatus.PENDING, TicketStatus.RESOLVED, TicketStatus.CLOSED] def _priorities(): return [TicketPriority.LOW, TicketPriority.MEDIUM, TicketPriority.HIGH, TicketPriority.CRITICAL] def _categories(): return [TicketCategory.HARDWARE, TicketCategory.SOFTWARE, TicketCategory.NETWORK, TicketCategory.ACCESS, TicketCategory.EMAIL, TicketCategory.PRINTER, TicketCategory.PHONE, TicketCategory.SECURITY, TicketCategory.OTHER]