04/07 updated password reset, ticket templates, and satisfaction survey
This commit is contained in:
+123
-1
@@ -11,7 +11,8 @@ from werkzeug.utils import secure_filename
|
||||
import bleach
|
||||
from app import db, limiter
|
||||
from app.models import (User, Ticket, Comment, ActivityLog, KnowledgeBase,
|
||||
KBAttachment, UserRole, TicketStatus, CannedResponse)
|
||||
KBAttachment, UserRole, TicketStatus, CannedResponse,
|
||||
TicketTemplate, TicketSatisfaction)
|
||||
from app.services.log_service import log_action, log_ticket_history
|
||||
from app.services.validation_service import validate_password, validate_file
|
||||
|
||||
@@ -1033,6 +1034,127 @@ def bulk_ticket_action():
|
||||
))
|
||||
|
||||
|
||||
# ─── Ticket Templates ────────────────────────────────────────────────────────
|
||||
|
||||
@admin_bp.route('/ticket-templates')
|
||||
@login_required
|
||||
@it_required
|
||||
def ticket_templates():
|
||||
templates = TicketTemplate.query.order_by(
|
||||
TicketTemplate.sort_order, TicketTemplate.name
|
||||
).all()
|
||||
return render_template('admin/ticket_templates.html', templates=templates)
|
||||
|
||||
|
||||
@admin_bp.route('/ticket-templates/new', methods=['GET', 'POST'])
|
||||
@login_required
|
||||
@it_required
|
||||
def ticket_template_new():
|
||||
if request.method == 'POST':
|
||||
name = request.form.get('name', '').strip()
|
||||
category = request.form.get('category', 'other')
|
||||
priority = request.form.get('priority', 'medium')
|
||||
title_hint = request.form.get('title_hint', '').strip()
|
||||
description= request.form.get('description', '').strip()
|
||||
icon = request.form.get('icon', 'bi-file-text').strip()
|
||||
sort_order = request.form.get('sort_order', 0, type=int)
|
||||
is_active = bool(request.form.get('is_active'))
|
||||
if not name:
|
||||
flash('Template name is required.', 'danger')
|
||||
return render_template('admin/ticket_template_edit.html',
|
||||
t=None, categories=_categories_list(),
|
||||
priorities=_priorities_list())
|
||||
t = TicketTemplate(
|
||||
name=name, category=category, priority=priority,
|
||||
title_hint=title_hint, description=description,
|
||||
icon=icon, sort_order=sort_order, is_active=is_active,
|
||||
created_by=current_user.id,
|
||||
)
|
||||
db.session.add(t)
|
||||
db.session.flush()
|
||||
log_action(current_user.id, 'ticket_template_create', 'ticket_template', t.id,
|
||||
f'name={name}')
|
||||
db.session.commit()
|
||||
logger.info(f'[TEMPLATE CREATE] id={t.id} name={name} by user_id={current_user.id}')
|
||||
flash(f'Template "{name}" created.', 'success')
|
||||
return redirect(url_for('admin.ticket_templates'))
|
||||
return render_template('admin/ticket_template_edit.html',
|
||||
t=None, categories=_categories_list(),
|
||||
priorities=_priorities_list())
|
||||
|
||||
|
||||
@admin_bp.route('/ticket-templates/<int:tmpl_id>/edit', methods=['GET', 'POST'])
|
||||
@login_required
|
||||
@it_required
|
||||
def ticket_template_edit(tmpl_id):
|
||||
t = db.session.get(TicketTemplate, tmpl_id) or abort(404)
|
||||
if request.method == 'POST':
|
||||
t.name = request.form.get('name', t.name).strip()
|
||||
t.category = request.form.get('category', t.category)
|
||||
t.priority = request.form.get('priority', t.priority)
|
||||
t.title_hint = request.form.get('title_hint', '').strip()
|
||||
t.description = request.form.get('description', '').strip()
|
||||
t.icon = request.form.get('icon', 'bi-file-text').strip()
|
||||
t.sort_order = request.form.get('sort_order', 0, type=int)
|
||||
t.is_active = bool(request.form.get('is_active'))
|
||||
log_action(current_user.id, 'ticket_template_edit', 'ticket_template', t.id,
|
||||
f'name={t.name}')
|
||||
db.session.commit()
|
||||
logger.info(f'[TEMPLATE EDIT] id={t.id} by user_id={current_user.id}')
|
||||
flash(f'Template "{t.name}" updated.', 'success')
|
||||
return redirect(url_for('admin.ticket_templates'))
|
||||
return render_template('admin/ticket_template_edit.html',
|
||||
t=t, categories=_categories_list(),
|
||||
priorities=_priorities_list())
|
||||
|
||||
|
||||
@admin_bp.route('/ticket-templates/<int:tmpl_id>/delete', methods=['POST'])
|
||||
@login_required
|
||||
@it_required
|
||||
def ticket_template_delete(tmpl_id):
|
||||
t = db.session.get(TicketTemplate, tmpl_id) or abort(404)
|
||||
name = t.name
|
||||
log_action(current_user.id, 'ticket_template_delete', 'ticket_template', t.id,
|
||||
f'name={name}')
|
||||
logger.info(f'[TEMPLATE DELETE] id={t.id} name={name} by user_id={current_user.id}')
|
||||
db.session.delete(t)
|
||||
db.session.commit()
|
||||
flash(f'Template "{name}" deleted.', 'success')
|
||||
return redirect(url_for('admin.ticket_templates'))
|
||||
|
||||
|
||||
# ─── Satisfaction Survey Report ───────────────────────────────────────────────
|
||||
|
||||
@admin_bp.route('/satisfaction')
|
||||
@login_required
|
||||
@it_required
|
||||
def satisfaction_report():
|
||||
surveys = TicketSatisfaction.query.filter(
|
||||
TicketSatisfaction.rating.isnot(None)
|
||||
).order_by(TicketSatisfaction.submitted_at.desc()).all()
|
||||
total = len(surveys)
|
||||
avg_rating = round(sum(s.rating for s in surveys) / total, 2) if total else None
|
||||
dist = {i: sum(1 for s in surveys if s.rating == i) for i in range(1, 6)}
|
||||
pending = TicketSatisfaction.query.filter_by(rating=None).count()
|
||||
return render_template('admin/satisfaction_report.html',
|
||||
surveys=surveys, total=total,
|
||||
avg_rating=avg_rating, dist=dist, pending=pending)
|
||||
|
||||
|
||||
def _categories_list():
|
||||
from app.models import TicketCategory
|
||||
return [TicketCategory.HARDWARE, TicketCategory.SOFTWARE,
|
||||
TicketCategory.NETWORK, TicketCategory.ACCESS,
|
||||
TicketCategory.EMAIL, TicketCategory.PRINTER,
|
||||
TicketCategory.PHONE, TicketCategory.SECURITY, TicketCategory.OTHER]
|
||||
|
||||
|
||||
def _priorities_list():
|
||||
from app.models import TicketPriority
|
||||
return [TicketPriority.LOW, TicketPriority.MEDIUM,
|
||||
TicketPriority.HIGH, TicketPriority.CRITICAL]
|
||||
|
||||
|
||||
def _roles():
|
||||
return [UserRole.EMPLOYEE, UserRole.IT_STAFF, UserRole.ADMIN]
|
||||
|
||||
|
||||
@@ -188,6 +188,126 @@ def profile():
|
||||
return render_template('auth/profile.html')
|
||||
|
||||
|
||||
|
||||
|
||||
@auth_bp.route('/forgot-password', methods=['GET', 'POST'])
|
||||
@limiter.limit('5 per hour')
|
||||
def forgot_password():
|
||||
"""Show the forgot-password form and send a reset email on POST."""
|
||||
if current_user.is_authenticated:
|
||||
return redirect(url_for('tickets.dashboard'))
|
||||
|
||||
if request.method == 'POST':
|
||||
email = request.form.get('email', '').strip().lower()
|
||||
user = User.query.filter_by(email=email, is_active=True).first()
|
||||
|
||||
# Always show the same message — prevents user enumeration
|
||||
flash('If that email is registered, a password reset link has been sent.', 'info')
|
||||
|
||||
if user:
|
||||
from app.models import PasswordResetToken
|
||||
# Invalidate any existing unused tokens for this user
|
||||
PasswordResetToken.query.filter_by(user_id=user.id).delete()
|
||||
raw, _token = PasswordResetToken.generate(user.id)
|
||||
db.session.commit()
|
||||
logger.info(f'[AUTH RESET REQUEST] user_id={user.id} email={email}')
|
||||
|
||||
reset_url = url_for('auth.reset_password', token=raw, _external=True)
|
||||
_send_reset_email(user, reset_url)
|
||||
|
||||
return redirect(url_for('auth.login'))
|
||||
|
||||
return render_template('auth/forgot_password.html')
|
||||
|
||||
|
||||
@auth_bp.route('/reset-password/<token>', methods=['GET', 'POST'])
|
||||
@limiter.limit('10 per hour')
|
||||
def reset_password(token):
|
||||
"""Validate the reset token and allow the user to set a new password."""
|
||||
if current_user.is_authenticated:
|
||||
return redirect(url_for('tickets.dashboard'))
|
||||
|
||||
from app.models import PasswordResetToken
|
||||
token_row = PasswordResetToken.verify(token)
|
||||
if not token_row:
|
||||
flash('This password reset link is invalid or has expired. Please request a new one.', 'danger')
|
||||
return redirect(url_for('auth.forgot_password'))
|
||||
|
||||
if request.method == 'POST':
|
||||
password = request.form.get('password', '')
|
||||
confirm = request.form.get('confirm_password', '')
|
||||
pw_error = validate_password(password, confirm)
|
||||
if pw_error:
|
||||
flash(pw_error, 'danger')
|
||||
return render_template('auth/reset_password.html', token=token)
|
||||
|
||||
user = token_row.user
|
||||
user.set_password(password)
|
||||
db.session.delete(token_row) # single-use — delete immediately
|
||||
log_action(user.id, 'password_reset', 'user', user.id)
|
||||
db.session.commit()
|
||||
logger.info(f'[AUTH RESET COMPLETE] user_id={user.id}')
|
||||
flash('Password updated successfully. You may now log in.', 'success')
|
||||
return redirect(url_for('auth.login'))
|
||||
|
||||
return render_template('auth/reset_password.html', token=token)
|
||||
|
||||
|
||||
def _send_reset_email(user, reset_url):
|
||||
"""Send the password reset email in a background thread."""
|
||||
from threading import Thread
|
||||
from flask_mail import Message
|
||||
from app import mail
|
||||
|
||||
html = f"""
|
||||
<html><body style="font-family:Arial,sans-serif;background:#f4f4f4;padding:20px;">
|
||||
<div style="max-width:520px;margin:0 auto;background:#fff;border-radius:10px;
|
||||
overflow:hidden;box-shadow:0 2px 12px rgba(0,0,0,.08);">
|
||||
<div style="background:#1e293b;padding:24px 32px;">
|
||||
<h1 style="color:#fff;margin:0;font-size:20px;">🔐 Password Reset Request</h1>
|
||||
</div>
|
||||
<div style="padding:32px;">
|
||||
<p style="color:#334155;margin-top:0;">Hi {user.full_name},</p>
|
||||
<p style="color:#334155;">We received a request to reset your TechDesk password.
|
||||
Click the button below to choose a new one.</p>
|
||||
<p style="text-align:center;margin:28px 0;">
|
||||
<a href="{reset_url}"
|
||||
style="display:inline-block;background:#2563eb;color:#fff;padding:13px 32px;
|
||||
border-radius:8px;text-decoration:none;font-weight:600;font-size:15px;">
|
||||
Reset My Password
|
||||
</a>
|
||||
</p>
|
||||
<p style="color:#64748b;font-size:13px;">This link expires in <strong>1 hour</strong>.
|
||||
If you did not request a password reset, you can safely ignore this email.</p>
|
||||
<p style="color:#64748b;font-size:12px;word-break:break-all;">
|
||||
Or paste this link into your browser:<br/>{reset_url}
|
||||
</p>
|
||||
</div>
|
||||
<div style="background:#f8fafc;padding:16px 32px;text-align:center;
|
||||
color:#94a3b8;font-size:11px;border-top:1px solid #e2e8f0;">
|
||||
TechDesk IT Helpdesk • This is an automated message.
|
||||
</div>
|
||||
</div>
|
||||
</body></html>"""
|
||||
|
||||
msg = Message(
|
||||
subject = 'TechDesk — Password Reset Request',
|
||||
recipients = [user.email],
|
||||
html = html,
|
||||
)
|
||||
|
||||
def _send():
|
||||
from flask import current_app
|
||||
with current_app.app_context():
|
||||
try:
|
||||
mail.send(msg)
|
||||
logger.info(f'[AUTH RESET EMAIL SENT] user_id={user.id}')
|
||||
except Exception as exc:
|
||||
logger.error(f'[AUTH RESET EMAIL FAILED] user_id={user.id} {exc}')
|
||||
|
||||
Thread(target=_send, daemon=True).start()
|
||||
|
||||
|
||||
@auth_bp.route('/avatar/<string:filename>')
|
||||
@login_required
|
||||
def serve_avatar(filename):
|
||||
|
||||
+55
-2
@@ -10,10 +10,11 @@ from app import db
|
||||
from app.models import (Ticket, Comment, Attachment, Notification,
|
||||
TicketStatus, TicketPriority, TicketCategory,
|
||||
User, UserRole, KnowledgeBase, TicketLink, CannedResponse,
|
||||
KBFeedback)
|
||||
KBFeedback, TicketTemplate, TicketSatisfaction)
|
||||
from app.services.notification_service import (
|
||||
notify_new_ticket, notify_status_change,
|
||||
notify_comment_added, notify_assignment,
|
||||
send_satisfaction_survey,
|
||||
)
|
||||
from app.services.log_service import log_action, log_ticket_history
|
||||
from app.services.sla_service import clear_sla_notification
|
||||
@@ -187,8 +188,12 @@ def create_ticket():
|
||||
flash(f'Ticket {ticket.ticket_number} created successfully!', 'success')
|
||||
return redirect(url_for('tickets.ticket_detail', ticket_id=ticket.id))
|
||||
|
||||
templates = TicketTemplate.query.filter_by(is_active=True).order_by(
|
||||
TicketTemplate.sort_order, TicketTemplate.name
|
||||
).all()
|
||||
return render_template('tickets/create.html',
|
||||
categories=_categories(), priorities=_priorities())
|
||||
categories=_categories(), priorities=_priorities(),
|
||||
templates=templates)
|
||||
|
||||
|
||||
# ─── Create Ticket on Behalf of Employee (IT Staff Only) ─────────────────────
|
||||
@@ -530,6 +535,8 @@ def update_ticket(ticket_id):
|
||||
|
||||
if new_status != old_status:
|
||||
notify_status_change(ticket, old_status, current_user)
|
||||
if new_status == TicketStatus.RESOLVED:
|
||||
send_satisfaction_survey(ticket)
|
||||
|
||||
flash('Ticket updated successfully.', 'success')
|
||||
return redirect(url_for('tickets.ticket_detail', ticket_id=ticket.id))
|
||||
@@ -917,6 +924,52 @@ def kb_feedback(article_id):
|
||||
})
|
||||
|
||||
|
||||
# ─── Ticket Survey ────────────────────────────────────────────────────────────
|
||||
|
||||
@tickets_bp.route('/survey/<token>', methods=['GET', 'POST'])
|
||||
def ticket_survey(token):
|
||||
"""Public survey endpoint — no login required.
|
||||
|
||||
The employee clicks a star in the resolution email which hits this route
|
||||
with ?rating=N. A GET with rating pre-selects the star; POST submits
|
||||
the full form (rating + optional comment).
|
||||
"""
|
||||
survey = TicketSatisfaction.query.filter_by(survey_token=token).first()
|
||||
if not survey:
|
||||
return render_template('tickets/survey_invalid.html'), 404
|
||||
|
||||
if survey.submitted:
|
||||
return render_template('tickets/survey_done.html', survey=survey)
|
||||
|
||||
# Star-click from email: rating is in query string → auto-submit
|
||||
quick_rating = request.args.get('rating', type=int)
|
||||
|
||||
if request.method == 'POST' or quick_rating:
|
||||
rating = quick_rating or request.form.get('rating', type=int)
|
||||
comment = request.form.get('comment', '').strip()
|
||||
|
||||
if not rating or not (1 <= rating <= 5):
|
||||
flash('Please select a rating between 1 and 5 stars.', 'danger')
|
||||
return render_template('tickets/survey.html', survey=survey)
|
||||
|
||||
survey.rating = rating
|
||||
survey.comment = comment or None
|
||||
survey.submitted_at = datetime.utcnow()
|
||||
log_action(
|
||||
survey.user_id, 'survey_submit', 'ticket', survey.ticket_id,
|
||||
f'rating={rating}'
|
||||
)
|
||||
db.session.commit()
|
||||
logger.info(
|
||||
f'[SURVEY SUBMIT] ticket_id={survey.ticket_id} '
|
||||
f'user_id={survey.user_id} rating={rating}'
|
||||
)
|
||||
return render_template('tickets/survey_done.html', survey=survey)
|
||||
|
||||
return render_template('tickets/survey.html', survey=survey,
|
||||
quick_rating=quick_rating)
|
||||
|
||||
|
||||
# ─── Helpers ─────────────────────────────────────────────────────────────────
|
||||
|
||||
def _sla_due_date(priority: str) -> 'datetime':
|
||||
|
||||
Reference in New Issue
Block a user