6c86f0f571
- integrated request-module into module registry - moved backend into modules/request-module - added manifest.json and module.py - implemented dynamic router mounting - implemented dynamic static mounting - removed direct dependencies from platform core - verified startup with request-module - verified startup without request-module - added implementation_report_003.md
218 lines
8.1 KiB
Python
218 lines
8.1 KiB
Python
"""Ticket service."""
|
|
|
|
from typing import List, Optional
|
|
from sqlalchemy.orm import Session
|
|
from fastapi import HTTPException, status
|
|
from sqlalchemy import func, and_, or_
|
|
from datetime import datetime
|
|
from request_app.models.ticket import Ticket
|
|
from request_app.models.comment import Comment
|
|
from request_app.models.user import User
|
|
from request_app.models.priority import Priority
|
|
from request_app.models.status import Status
|
|
from request_app.models.category import Category
|
|
from request_app.models.extra import Company, Location
|
|
from request_app.schemas.ticket import TicketCreate, TicketUpdate, TicketResponse
|
|
from request_app.core.exceptions import NotFoundException, ValidationException
|
|
from request_app.core.logging import ticket_logger
|
|
from request_app.services.user_service import UserService
|
|
|
|
|
|
class TicketService:
|
|
"""Ticket service."""
|
|
|
|
def __init__(self, db: Session):
|
|
self.db = db
|
|
self.user_service = UserService(db)
|
|
|
|
def get_ticket_by_id(self, ticket_id: int) -> Ticket:
|
|
"""Get ticket by ID."""
|
|
ticket = self.db.query(Ticket).filter(Ticket.id == ticket_id).first()
|
|
if not ticket:
|
|
raise NotFoundException(f"Ticket with id {ticket_id} not found")
|
|
return ticket
|
|
|
|
def get_tickets(
|
|
self,
|
|
page: int,
|
|
page_size: int,
|
|
status_id: Optional[int] = None,
|
|
priority_id: Optional[int] = None,
|
|
assigned_to_id: Optional[int] = None,
|
|
search: Optional[str] = None,
|
|
user_id: Optional[int] = None
|
|
) -> tuple[List[Ticket], int]:
|
|
"""Get paginated list of tickets."""
|
|
query = self.db.query(Ticket)
|
|
|
|
# Filters
|
|
if status_id:
|
|
query = query.filter(Ticket.status_id == status_id)
|
|
if priority_id:
|
|
query = query.filter(Ticket.priority_id == priority_id)
|
|
if assigned_to_id:
|
|
query = query.filter(Ticket.assigned_to_id == assigned_to_id)
|
|
|
|
# Search filter
|
|
if search:
|
|
search_term = f"%{search}%"
|
|
query = query.filter(
|
|
(Ticket.subject.ilike(search_term)) |
|
|
(Ticket.description.ilike(search_term))
|
|
)
|
|
|
|
# User-specific tickets (only show tickets they created or are assigned to)
|
|
if user_id:
|
|
query = query.filter(
|
|
or_(
|
|
Ticket.opened_by == user_id,
|
|
Ticket.assigned_to_id == user_id
|
|
)
|
|
)
|
|
|
|
# Get total count
|
|
total = query.count()
|
|
|
|
# Get paginated results
|
|
tickets = query.order_by(Ticket.created_at.desc()).offset((page - 1) * page_size).limit(page_size).all()
|
|
|
|
return tickets, total
|
|
|
|
def create_ticket(self, ticket_data: TicketCreate, user_id: int) -> Ticket:
|
|
"""Create a new ticket."""
|
|
# Validate user exists
|
|
self.user_service.get_user_by_id(user_id)
|
|
|
|
# Validate category, priority, status exist
|
|
self.db.query(Category).filter(Category.id == ticket_data.category_id).first()
|
|
self.db.query(Priority).filter(Priority.id == ticket_data.priority_id).first()
|
|
self.db.query(Status).filter(Status.id == ticket_data.status_id).first()
|
|
|
|
# Create ticket
|
|
ticket = Ticket(
|
|
subject=ticket_data.subject,
|
|
description=ticket_data.description,
|
|
category_id=ticket_data.category_id,
|
|
priority_id=ticket_data.priority_id,
|
|
status_id=ticket_data.status_id,
|
|
source=ticket_data.source,
|
|
opened_by=user_id,
|
|
assigned_to_id=ticket_data.assigned_to_id,
|
|
created_at=datetime.utcnow()
|
|
)
|
|
|
|
self.db.add(ticket)
|
|
self.db.commit()
|
|
self.db.refresh(ticket)
|
|
|
|
# Add ticket number to subject
|
|
ticket.subject = f"[#{ticket.id}] {ticket.subject}"
|
|
self.db.commit()
|
|
|
|
ticket_logger.info(f"Ticket created: [{ticket.id}] '{ticket.subject}' by user_id={user_id} source={ticket.source}")
|
|
|
|
# Log ticket event
|
|
from request_app.services.ticket_event_service import TicketEventService
|
|
TicketEventService(self.db).log(ticket.id, 'created', f'Тикет создан: {ticket.subject}', user_id)
|
|
|
|
# Send notification
|
|
self._notify(ticket, 'ticket_created', user_id)
|
|
|
|
return ticket
|
|
|
|
def update_ticket(self, ticket_id: int, ticket_data: TicketUpdate, user_id: int) -> Ticket:
|
|
"""Update ticket."""
|
|
ticket = self.get_ticket_by_id(ticket_id)
|
|
|
|
# Validate assigned_to user exists if provided
|
|
if ticket_data.assigned_to_id:
|
|
self.user_service.get_user_by_id(ticket_data.assigned_to_id)
|
|
|
|
# Track if assignment changed
|
|
assignment_changed = (
|
|
ticket_data.assigned_to_id is not None
|
|
and ticket_data.assigned_to_id != ticket.assigned_to_id
|
|
)
|
|
|
|
# Update fields
|
|
if ticket_data.subject is not None:
|
|
ticket.subject = ticket_data.subject
|
|
if ticket_data.description is not None:
|
|
ticket.description = ticket_data.description
|
|
if ticket_data.category_id is not None:
|
|
ticket.category_id = ticket_data.category_id
|
|
if ticket_data.priority_id is not None:
|
|
ticket.priority_id = ticket_data.priority_id
|
|
if ticket_data.status_id is not None:
|
|
ticket.status_id = ticket_data.status_id
|
|
if ticket_data.assigned_to_id is not None:
|
|
ticket.assigned_to_id = ticket_data.assigned_to_id
|
|
if ticket_data.closed_at is not None:
|
|
ticket.closed_at = ticket_data.closed_at
|
|
|
|
self.db.commit()
|
|
self.db.refresh(ticket)
|
|
|
|
ticket_logger.info(f"Ticket updated: [{ticket_id}] by user_id={user_id}")
|
|
|
|
# Send notifications
|
|
if assignment_changed:
|
|
self._notify(ticket, 'ticket_assigned', user_id)
|
|
else:
|
|
self._notify(ticket, 'ticket_updated', user_id)
|
|
|
|
return ticket
|
|
|
|
def delete_ticket(self, ticket_id: int) -> dict:
|
|
"""Delete ticket."""
|
|
ticket = self.get_ticket_by_id(ticket_id)
|
|
|
|
self.db.delete(ticket)
|
|
self.db.commit()
|
|
|
|
ticket_logger.info(f"Ticket deleted: [{ticket_id}]")
|
|
return {"message": "Ticket deleted successfully"}
|
|
|
|
def add_comment(self, ticket_id: int, comment_text: str, user_id: int) -> Comment:
|
|
"""Add comment to ticket."""
|
|
ticket = self.get_ticket_by_id(ticket_id)
|
|
user = self.user_service.get_user_by_id(user_id)
|
|
|
|
comment = Comment(
|
|
ticket_id=ticket_id,
|
|
created_by=user_id,
|
|
comment_text=comment_text
|
|
)
|
|
|
|
self.db.add(comment)
|
|
self.db.commit()
|
|
self.db.refresh(comment)
|
|
|
|
ticket_logger.info(f"Comment added to ticket [{ticket_id}] by user_id={user_id}")
|
|
return comment
|
|
|
|
def get_ticket_comments(self, ticket_id: int) -> List[Comment]:
|
|
"""Get all comments for a ticket."""
|
|
comments = self.db.query(Comment).filter(Comment.ticket_id == ticket_id).order_by(Comment.created_at.asc()).all()
|
|
return comments
|
|
|
|
def _notify(self, ticket: Ticket, event_type: str, actor_user_id: int):
|
|
"""Send notification via template service."""
|
|
from request_app.core.logging import logger
|
|
try:
|
|
from request_app.services.notification_service_extended import NotificationServiceExtended
|
|
svc = NotificationServiceExtended(self.db)
|
|
|
|
initiator = self.db.query(User).filter(User.id == actor_user_id).first()
|
|
specialist = None
|
|
if ticket.assigned_to_id:
|
|
specialist = self.db.query(User).filter(User.id == ticket.assigned_to_id).first()
|
|
|
|
logger.info(f"_notify: ticket={ticket.id} event={event_type} initiator={initiator.email if initiator else None} specialist={specialist.email if specialist else None}")
|
|
|
|
# Reload ticket with relationships
|
|
ticket = self.db.query(Ticket).filter(Ticket.id == ticket.id).first()
|
|
svc.send_ticket_notification(ticket, event_type, initiator, specialist)
|
|
except Exception as e:
|
|
logger.error(f"Notification error: {e}", exc_info=True)
|