ервый импорт проекта
This commit is contained in:
@@ -0,0 +1,11 @@
|
||||
"""Services package."""
|
||||
|
||||
from app.services.user_service import UserService
|
||||
from app.services.ticket_service import TicketService
|
||||
from app.services.notification_service import NotificationService
|
||||
|
||||
__all__ = [
|
||||
"UserService",
|
||||
"TicketService",
|
||||
"NotificationService",
|
||||
]
|
||||
@@ -0,0 +1,226 @@
|
||||
"""Email message service."""
|
||||
|
||||
from typing import List, Optional
|
||||
from sqlalchemy.orm import Session
|
||||
from datetime import datetime
|
||||
|
||||
from app.models.email_message import EmailMessage, EmailAttachment
|
||||
from app.models.ticket import Ticket
|
||||
from app.core.exceptions import NotFoundException
|
||||
from app.integrations.email import EmailClient
|
||||
from app.core.logging import logger
|
||||
|
||||
|
||||
class EmailMessageService:
|
||||
"""Email message service for ticket conversation threads."""
|
||||
|
||||
def __init__(self, db: Session):
|
||||
self.db = db
|
||||
|
||||
def get_ticket_emails(self, ticket_id: int) -> List[EmailMessage]:
|
||||
"""Get all email messages for a ticket, ordered by date."""
|
||||
# Verify ticket exists
|
||||
ticket = self.db.query(Ticket).filter(Ticket.id == ticket_id).first()
|
||||
if not ticket:
|
||||
raise NotFoundException(f"Ticket {ticket_id} not found")
|
||||
|
||||
return (
|
||||
self.db.query(EmailMessage)
|
||||
.filter(EmailMessage.ticket_id == ticket_id)
|
||||
.order_by(EmailMessage.created_at.asc())
|
||||
.all()
|
||||
)
|
||||
|
||||
def get_email_by_id(self, email_id: int) -> EmailMessage:
|
||||
"""Get email message by ID."""
|
||||
email = self.db.query(EmailMessage).filter(EmailMessage.id == email_id).first()
|
||||
if not email:
|
||||
raise NotFoundException(f"Email message {email_id} not found")
|
||||
return email
|
||||
|
||||
def create_incoming_email(
|
||||
self,
|
||||
ticket_id: int,
|
||||
from_address: str,
|
||||
to_addresses: str,
|
||||
subject: str,
|
||||
body_text: Optional[str] = None,
|
||||
body_html: Optional[str] = None,
|
||||
message_id: Optional[str] = None,
|
||||
in_reply_to: Optional[str] = None,
|
||||
references: Optional[str] = None,
|
||||
cc_addresses: Optional[str] = None,
|
||||
received_at: Optional[datetime] = None
|
||||
) -> EmailMessage:
|
||||
"""Create an incoming email message."""
|
||||
email = EmailMessage(
|
||||
ticket_id=ticket_id,
|
||||
direction='incoming',
|
||||
message_id=message_id,
|
||||
in_reply_to=in_reply_to,
|
||||
references=references,
|
||||
from_address=from_address,
|
||||
to_addresses=to_addresses,
|
||||
cc_addresses=cc_addresses,
|
||||
subject=subject,
|
||||
body_text=body_text,
|
||||
body_html=body_html,
|
||||
is_read=False,
|
||||
received_at=received_at or datetime.utcnow()
|
||||
)
|
||||
self.db.add(email)
|
||||
self.db.commit()
|
||||
self.db.refresh(email)
|
||||
return email
|
||||
|
||||
def send_reply(
|
||||
self,
|
||||
ticket_id: int,
|
||||
user_id: int,
|
||||
to_addresses: str,
|
||||
subject: str,
|
||||
body_text: Optional[str] = None,
|
||||
body_html: Optional[str] = None,
|
||||
in_reply_to: Optional[str] = None,
|
||||
cc_addresses: Optional[str] = None
|
||||
) -> EmailMessage:
|
||||
"""Send a reply email and save it to the conversation."""
|
||||
from app.services.email_outbox_service import EmailOutboxService
|
||||
|
||||
email_client = EmailClient(db_session=self.db)
|
||||
sent_at = None
|
||||
|
||||
try:
|
||||
result = email_client.send_email(
|
||||
to=to_addresses,
|
||||
subject=subject,
|
||||
body=body_text or "",
|
||||
html_body=body_html,
|
||||
cc=cc_addresses.split(",") if cc_addresses else None
|
||||
)
|
||||
if result.get("status") == "success":
|
||||
sent_at = datetime.utcnow()
|
||||
else:
|
||||
# Queue for retry
|
||||
outbox = EmailOutboxService(self.db)
|
||||
outbox.enqueue(
|
||||
to_addresses=to_addresses, subject=subject,
|
||||
body_text=body_text, body_html=body_html,
|
||||
cc_addresses=cc_addresses, ticket_id=ticket_id, user_id=user_id
|
||||
)
|
||||
logger.warning(f"Email send failed, queued: {result.get('error')}")
|
||||
except Exception as e:
|
||||
outbox = EmailOutboxService(self.db)
|
||||
outbox.enqueue(
|
||||
to_addresses=to_addresses, subject=subject,
|
||||
body_text=body_text, body_html=body_html,
|
||||
cc_addresses=cc_addresses, ticket_id=ticket_id, user_id=user_id
|
||||
)
|
||||
logger.warning(f"Email send error, queued: {e}")
|
||||
|
||||
# Always save to conversation
|
||||
email = EmailMessage(
|
||||
ticket_id=ticket_id,
|
||||
direction='outgoing',
|
||||
in_reply_to=in_reply_to,
|
||||
from_address=email_client.from_email,
|
||||
to_addresses=to_addresses,
|
||||
cc_addresses=cc_addresses,
|
||||
subject=subject,
|
||||
body_text=body_text,
|
||||
body_html=body_html,
|
||||
is_read=True,
|
||||
sent_at=sent_at,
|
||||
sent_by=user_id
|
||||
)
|
||||
self.db.add(email)
|
||||
self.db.commit()
|
||||
self.db.refresh(email)
|
||||
|
||||
return email
|
||||
|
||||
def forward_email(
|
||||
self,
|
||||
email_id: int,
|
||||
user_id: int,
|
||||
to_addresses: str,
|
||||
cc_addresses: Optional[str] = None,
|
||||
add_message: Optional[str] = None
|
||||
) -> EmailMessage:
|
||||
"""Forward an email to new recipients."""
|
||||
from app.services.email_outbox_service import EmailOutboxService
|
||||
|
||||
original = self.get_email_by_id(email_id)
|
||||
|
||||
subject = f"Fwd: {original.subject}" if original.subject else "Fwd: (no subject)"
|
||||
|
||||
body_parts = []
|
||||
if add_message:
|
||||
body_parts.append(add_message)
|
||||
body_parts.append("\n\n---------- Forwarded message ----------")
|
||||
|
||||
body_parts.append(f"From: {original.from_address}")
|
||||
body_parts.append(f"Date: {original.created_at}")
|
||||
body_parts.append(f"Subject: {original.subject}")
|
||||
body_parts.append(f"To: {original.to_addresses}")
|
||||
if original.cc_addresses:
|
||||
body_parts.append(f"CC: {original.cc_addresses}")
|
||||
body_parts.append("")
|
||||
body_parts.append(original.body_text or "(no content)")
|
||||
|
||||
body_text = "\n".join(body_parts)
|
||||
|
||||
email_client = EmailClient(db_session=self.db)
|
||||
sent_at = None
|
||||
|
||||
try:
|
||||
result = email_client.send_email(
|
||||
to=to_addresses,
|
||||
subject=subject,
|
||||
body=body_text,
|
||||
cc=cc_addresses.split(",") if cc_addresses else None
|
||||
)
|
||||
if result.get("status") == "success":
|
||||
sent_at = datetime.utcnow()
|
||||
else:
|
||||
outbox = EmailOutboxService(self.db)
|
||||
outbox.enqueue(
|
||||
to_addresses=to_addresses, subject=subject,
|
||||
body_text=body_text, cc_addresses=cc_addresses,
|
||||
ticket_id=original.ticket_id, user_id=user_id
|
||||
)
|
||||
logger.warning(f"Forward failed, queued: {result.get('error')}")
|
||||
except Exception as e:
|
||||
outbox = EmailOutboxService(self.db)
|
||||
outbox.enqueue(
|
||||
to_addresses=to_addresses, subject=subject,
|
||||
body_text=body_text, cc_addresses=cc_addresses,
|
||||
ticket_id=original.ticket_id, user_id=user_id
|
||||
)
|
||||
logger.warning(f"Forward error, queued: {e}")
|
||||
|
||||
email = EmailMessage(
|
||||
ticket_id=original.ticket_id,
|
||||
direction='outgoing',
|
||||
from_address=email_client.from_email,
|
||||
to_addresses=to_addresses,
|
||||
cc_addresses=cc_addresses,
|
||||
subject=subject,
|
||||
body_text=body_text,
|
||||
is_read=True,
|
||||
sent_at=sent_at,
|
||||
sent_by=user_id
|
||||
)
|
||||
self.db.add(email)
|
||||
self.db.commit()
|
||||
self.db.refresh(email)
|
||||
|
||||
return email
|
||||
|
||||
def mark_as_read(self, email_id: int) -> EmailMessage:
|
||||
"""Mark email as read."""
|
||||
email = self.get_email_by_id(email_id)
|
||||
email.is_read = True
|
||||
self.db.commit()
|
||||
self.db.refresh(email)
|
||||
return email
|
||||
@@ -0,0 +1,136 @@
|
||||
"""Email outbox service - queue for reliable email delivery."""
|
||||
|
||||
from typing import Optional, List
|
||||
from sqlalchemy.orm import Session
|
||||
from datetime import datetime
|
||||
|
||||
from app.models.email_outbox import EmailOutbox
|
||||
from app.core.logging import logger
|
||||
|
||||
|
||||
class EmailOutboxService:
|
||||
"""Manages email send queue."""
|
||||
|
||||
def __init__(self, db: Session):
|
||||
self.db = db
|
||||
|
||||
def enqueue(
|
||||
self,
|
||||
to_addresses: str,
|
||||
subject: str,
|
||||
body_text: Optional[str] = None,
|
||||
body_html: Optional[str] = None,
|
||||
cc_addresses: Optional[str] = None,
|
||||
ticket_id: Optional[int] = None,
|
||||
user_id: Optional[int] = None,
|
||||
max_retries: int = 5
|
||||
) -> EmailOutbox:
|
||||
"""Add email to send queue."""
|
||||
entry = EmailOutbox(
|
||||
ticket_id=ticket_id,
|
||||
user_id=user_id,
|
||||
to_addresses=to_addresses,
|
||||
cc_addresses=cc_addresses,
|
||||
subject=subject,
|
||||
body_text=body_text,
|
||||
body_html=body_html,
|
||||
status="pending",
|
||||
max_retries=max_retries
|
||||
)
|
||||
self.db.add(entry)
|
||||
self.db.commit()
|
||||
self.db.refresh(entry)
|
||||
logger.info(f"Email queued: id={entry.id}, to={to_addresses}, subject='{subject}'")
|
||||
return entry
|
||||
|
||||
def get_pending(self, limit: int = 10) -> List[EmailOutbox]:
|
||||
"""Get pending emails ready for sending."""
|
||||
return (
|
||||
self.db.query(EmailOutbox)
|
||||
.filter(EmailOutbox.status == "pending")
|
||||
.order_by(EmailOutbox.created_at.asc())
|
||||
.limit(limit)
|
||||
.all()
|
||||
)
|
||||
|
||||
def mark_sent(self, entry_id: int):
|
||||
"""Mark email as successfully sent."""
|
||||
entry = self.db.query(EmailOutbox).filter(EmailOutbox.id == entry_id).first()
|
||||
if entry:
|
||||
entry.status = "sent"
|
||||
entry.sent_at = datetime.utcnow()
|
||||
self.db.commit()
|
||||
|
||||
def mark_failed(self, entry_id: int, error: str):
|
||||
"""Mark email attempt as failed, increment retry count."""
|
||||
entry = self.db.query(EmailOutbox).filter(EmailOutbox.id == entry_id).first()
|
||||
if entry:
|
||||
entry.retries += 1
|
||||
entry.last_error = error
|
||||
if entry.retries >= entry.max_retries:
|
||||
entry.status = "failed"
|
||||
logger.error(f"Email permanently failed: id={entry_id}, to={entry.to_addresses}, error={error}")
|
||||
else:
|
||||
entry.status = "pending"
|
||||
logger.warning(f"Email send failed, will retry: id={entry_id}, attempt={entry.retries}/{entry.max_retries}")
|
||||
self.db.commit()
|
||||
|
||||
def process_queue(self) -> dict:
|
||||
"""Try to send all pending emails. Returns summary."""
|
||||
from app.integrations.email import EmailClient
|
||||
|
||||
pending = self.get_pending(limit=20)
|
||||
if not pending:
|
||||
return {"processed": 0, "sent": 0, "failed": 0}
|
||||
|
||||
try:
|
||||
client = EmailClient(db_session=self.db)
|
||||
except Exception as e:
|
||||
logger.error(f"Cannot create EmailClient for outbox: {e}")
|
||||
return {"processed": 0, "sent": 0, "failed": 0, "error": str(e)}
|
||||
|
||||
sent = 0
|
||||
failed = 0
|
||||
|
||||
for entry in pending:
|
||||
try:
|
||||
entry.status = "sending"
|
||||
self.db.commit()
|
||||
|
||||
result = client.send_email(
|
||||
to=entry.to_addresses,
|
||||
subject=entry.subject or "",
|
||||
body=entry.body_text or "",
|
||||
html_body=entry.body_html,
|
||||
cc=entry.cc_addresses.split(",") if entry.cc_addresses else None
|
||||
)
|
||||
|
||||
if result.get("status") == "success":
|
||||
self.mark_sent(entry.id)
|
||||
sent += 1
|
||||
else:
|
||||
self.mark_failed(entry.id, result.get("error", "Unknown error"))
|
||||
failed += 1
|
||||
|
||||
except Exception as e:
|
||||
self.mark_failed(entry.id, str(e))
|
||||
failed += 1
|
||||
|
||||
return {"processed": len(pending), "sent": sent, "failed": failed}
|
||||
|
||||
def reset_failed(self) -> int:
|
||||
"""Reset all failed emails back to pending for retry."""
|
||||
count = (
|
||||
self.db.query(EmailOutbox)
|
||||
.filter(EmailOutbox.status == "failed")
|
||||
.update({"status": "pending", "retries": 0, "last_error": None})
|
||||
)
|
||||
self.db.commit()
|
||||
return count
|
||||
|
||||
def get_stats(self) -> dict:
|
||||
"""Get queue statistics."""
|
||||
pending = self.db.query(EmailOutbox).filter(EmailOutbox.status == "pending").count()
|
||||
failed = self.db.query(EmailOutbox).filter(EmailOutbox.status == "failed").count()
|
||||
sent = self.db.query(EmailOutbox).filter(EmailOutbox.status == "sent").count()
|
||||
return {"pending": pending, "failed": failed, "sent": sent}
|
||||
@@ -0,0 +1,147 @@
|
||||
"""Email processing service - handles incoming emails."""
|
||||
|
||||
import re
|
||||
from typing import Optional, Tuple
|
||||
from sqlalchemy.orm import Session
|
||||
from app.models.ticket import Ticket
|
||||
from app.models.user import User
|
||||
from app.models.email_message import EmailMessage
|
||||
from app.core.logging import email_logger
|
||||
|
||||
|
||||
class EmailProcessor:
|
||||
"""Process incoming emails and link/create tickets."""
|
||||
|
||||
# Pattern to find ticket ID in subject: [#12345], RE: [#12345], Re: [#12345], etc.
|
||||
TICKET_ID_PATTERN = re.compile(r'\[#(\d+)\]')
|
||||
|
||||
def __init__(self, db: Session):
|
||||
self.db = db
|
||||
|
||||
def extract_ticket_id_from_subject(self, subject: str) -> Optional[int]:
|
||||
"""Extract ticket ID from email subject if present."""
|
||||
match = self.TICKET_ID_PATTERN.search(subject)
|
||||
if match:
|
||||
return int(match.group(1))
|
||||
return None
|
||||
|
||||
def find_or_create_ticket(
|
||||
self,
|
||||
subject: str,
|
||||
body: str,
|
||||
from_email: str,
|
||||
to_email: str,
|
||||
message_id: Optional[str] = None,
|
||||
in_reply_to: Optional[str] = None
|
||||
) -> Tuple[Ticket, bool]:
|
||||
"""
|
||||
Find existing ticket by ID in subject, or create new one.
|
||||
Returns (ticket, is_new).
|
||||
"""
|
||||
# Try to extract ticket ID from subject
|
||||
ticket_id = self.extract_ticket_id_from_subject(subject)
|
||||
|
||||
if ticket_id:
|
||||
# Try to find existing ticket
|
||||
ticket = self.db.query(Ticket).filter(Ticket.id == ticket_id).first()
|
||||
if ticket:
|
||||
email_logger.info(f"Found existing ticket #{ticket_id} for email from {from_email}")
|
||||
# Add email to existing ticket
|
||||
self._add_email_to_ticket(ticket, subject, body, from_email, to_email, message_id, in_reply_to)
|
||||
return ticket, False
|
||||
else:
|
||||
email_logger.warning(f"Ticket #{ticket_id} referenced in subject but not found")
|
||||
|
||||
# Find or create user
|
||||
user = self._find_or_create_user(from_email)
|
||||
|
||||
# Create new ticket
|
||||
email_logger.info(f"Creating new ticket from email by {from_email}")
|
||||
ticket = Ticket(
|
||||
subject=subject[:4000],
|
||||
description=body,
|
||||
category_id=self._get_default_category_id(),
|
||||
priority_id=self._get_default_priority_id(),
|
||||
status_id=self._get_default_status_id(),
|
||||
source='email',
|
||||
opened_by=user.id
|
||||
)
|
||||
self.db.add(ticket)
|
||||
self.db.commit()
|
||||
self.db.refresh(ticket)
|
||||
|
||||
# Add the email as a message
|
||||
self._add_email_to_ticket(ticket, subject, body, from_email, to_email, message_id, in_reply_to)
|
||||
|
||||
email_logger.info(f"Created ticket #{ticket.id}: {subject[:50]}")
|
||||
return ticket, True
|
||||
|
||||
def _add_email_to_ticket(
|
||||
self,
|
||||
ticket: Ticket,
|
||||
subject: str,
|
||||
body: str,
|
||||
from_email: str,
|
||||
to_email: str,
|
||||
message_id: Optional[str] = None,
|
||||
in_reply_to: Optional[str] = None
|
||||
):
|
||||
"""Add email message to ticket."""
|
||||
email_msg = EmailMessage(
|
||||
ticket_id=ticket.id,
|
||||
direction='incoming',
|
||||
message_id=message_id,
|
||||
in_reply_to=in_reply_to,
|
||||
from_address=from_email,
|
||||
to_addresses=to_email,
|
||||
subject=subject,
|
||||
body_text=body,
|
||||
body_html=body,
|
||||
is_read=False
|
||||
)
|
||||
self.db.add(email_msg)
|
||||
self.db.commit()
|
||||
|
||||
def _find_or_create_user(self, email: str) -> User:
|
||||
"""Find existing user by email or create new one (local cache only)."""
|
||||
user = self.db.query(User).filter(User.email == email).first()
|
||||
if not user:
|
||||
email_logger.info(f"Creating user cache from email: {email}")
|
||||
name_parts = email.split('@')[0].split('.')
|
||||
first_name = name_parts[0].capitalize() if name_parts else 'User'
|
||||
last_name = name_parts[1].capitalize() if len(name_parts) > 1 else ''
|
||||
|
||||
user = User(
|
||||
email=email,
|
||||
first_name=first_name,
|
||||
last_name=last_name,
|
||||
is_active=True
|
||||
)
|
||||
self.db.add(user)
|
||||
self.db.commit()
|
||||
self.db.refresh(user)
|
||||
return user
|
||||
|
||||
def _get_default_category_id(self) -> int:
|
||||
"""Get default category ID."""
|
||||
from app.models.category import Category
|
||||
cat = self.db.query(Category).first()
|
||||
return cat.id if cat else 1
|
||||
|
||||
def _get_default_priority_id(self) -> int:
|
||||
"""Get default priority ID."""
|
||||
from app.models.priority import Priority
|
||||
pri = self.db.query(Priority).filter(Priority.name.ilike('%обычн%')).first()
|
||||
if not pri:
|
||||
pri = self.db.query(Priority).first()
|
||||
return pri.id if pri else 1
|
||||
|
||||
def _get_default_status_id(self) -> int:
|
||||
"""Get default status ID (Open)."""
|
||||
from app.models.status import Status
|
||||
status = self.db.query(Status).filter(Status.name.ilike('%открыт%')).first()
|
||||
if not status:
|
||||
status = self.db.query(Status).filter(Status.is_final == False).first()
|
||||
if not status:
|
||||
status = self.db.query(Status).first()
|
||||
return status.id if status else 1
|
||||
@@ -0,0 +1,95 @@
|
||||
"""Notification service."""
|
||||
|
||||
from typing import List, Optional
|
||||
from sqlalchemy.orm import Session
|
||||
from datetime import datetime
|
||||
from app.models.notification import Notification
|
||||
from app.models.user import User
|
||||
|
||||
|
||||
class NotificationService:
|
||||
"""Notification service."""
|
||||
|
||||
def __init__(self, db: Session):
|
||||
self.db = db
|
||||
|
||||
def create_notification(
|
||||
self,
|
||||
user_id: int,
|
||||
ticket_id: int,
|
||||
notification_type: str,
|
||||
title: str,
|
||||
message: str,
|
||||
is_read: int = 0,
|
||||
is_delivered: int = 0
|
||||
) -> Notification:
|
||||
"""Create notification."""
|
||||
notification = Notification(
|
||||
user_id=user_id,
|
||||
ticket_id=ticket_id,
|
||||
type=notification_type,
|
||||
title=title,
|
||||
message=message,
|
||||
is_read=is_read,
|
||||
is_delivered=is_delivered
|
||||
)
|
||||
|
||||
self.db.add(notification)
|
||||
self.db.commit()
|
||||
self.db.refresh(notification)
|
||||
|
||||
return notification
|
||||
|
||||
def get_user_notifications(
|
||||
self,
|
||||
user_id: int,
|
||||
is_read: Optional[int] = None
|
||||
) -> List[Notification]:
|
||||
"""Get user notifications."""
|
||||
query = self.db.query(Notification).filter(Notification.user_id == user_id)
|
||||
|
||||
if is_read is not None:
|
||||
query = query.filter(Notification.is_read == is_read)
|
||||
|
||||
return query.order_by(Notification.created_at.desc()).all()
|
||||
|
||||
def mark_as_read(self, notification_id: int, user_id: int) -> Notification:
|
||||
"""Mark notification as read."""
|
||||
notification = self.db.query(Notification).filter(
|
||||
Notification.id == notification_id,
|
||||
Notification.user_id == user_id
|
||||
).first()
|
||||
|
||||
if not notification:
|
||||
raise ValueError("Notification not found")
|
||||
|
||||
notification.is_read = 1
|
||||
self.db.commit()
|
||||
self.db.refresh(notification)
|
||||
|
||||
return notification
|
||||
|
||||
def mark_all_as_read(self, user_id: int) -> int:
|
||||
"""Mark all notifications as read for user."""
|
||||
updated = self.db.query(Notification).filter(
|
||||
Notification.user_id == user_id,
|
||||
Notification.is_read == 0
|
||||
).update({"is_read": 1})
|
||||
|
||||
self.db.commit()
|
||||
|
||||
return updated
|
||||
|
||||
def delete_notification(self, notification_id: int, user_id: int) -> bool:
|
||||
"""Delete notification."""
|
||||
notification = self.db.query(Notification).filter(
|
||||
Notification.id == notification_id,
|
||||
Notification.user_id == user_id
|
||||
).first()
|
||||
|
||||
if notification:
|
||||
self.db.delete(notification)
|
||||
self.db.commit()
|
||||
return True
|
||||
|
||||
return False
|
||||
@@ -0,0 +1,365 @@
|
||||
"""Notification service with template support."""
|
||||
|
||||
import json
|
||||
from typing import List, Optional, Dict
|
||||
from sqlalchemy.orm import Session
|
||||
from datetime import datetime
|
||||
|
||||
from app.models.notification_template import NotificationTemplate, SavedFilter
|
||||
from app.models.notification import Notification
|
||||
from app.models.user import User
|
||||
from app.models.ticket import Ticket
|
||||
from app.integrations.email import EmailClient
|
||||
from app.integrations.sms import SMSClient
|
||||
from app.settings import get_settings
|
||||
|
||||
|
||||
class NotificationServiceExtended:
|
||||
"""Extended notification service with templates."""
|
||||
|
||||
def __init__(self, db: Session):
|
||||
self.db = db
|
||||
|
||||
def get_templates(self, event_type: Optional[str] = None) -> List[NotificationTemplate]:
|
||||
"""Get notification templates."""
|
||||
query = self.db.query(NotificationTemplate)
|
||||
if event_type:
|
||||
query = query.filter(NotificationTemplate.event_type == event_type)
|
||||
return query.all()
|
||||
|
||||
def get_template_by_id(self, template_id: int) -> Optional[NotificationTemplate]:
|
||||
"""Get template by ID."""
|
||||
return self.db.query(NotificationTemplate).filter(
|
||||
NotificationTemplate.id == template_id
|
||||
).first()
|
||||
|
||||
def create_template(self, **kwargs) -> NotificationTemplate:
|
||||
"""Create notification template."""
|
||||
template = NotificationTemplate(**kwargs)
|
||||
self.db.add(template)
|
||||
self.db.commit()
|
||||
self.db.refresh(template)
|
||||
return template
|
||||
|
||||
def update_template(self, template_id: int, **kwargs) -> NotificationTemplate:
|
||||
"""Update notification template."""
|
||||
template = self.get_template_by_id(template_id)
|
||||
if not template:
|
||||
raise ValueError(f"Template {template_id} not found")
|
||||
|
||||
for key, value in kwargs.items():
|
||||
if hasattr(template, key):
|
||||
setattr(template, key, value)
|
||||
|
||||
self.db.commit()
|
||||
self.db.refresh(template)
|
||||
return template
|
||||
|
||||
def delete_template(self, template_id: int) -> bool:
|
||||
"""Delete notification template."""
|
||||
template = self.get_template_by_id(template_id)
|
||||
if template:
|
||||
self.db.delete(template)
|
||||
self.db.commit()
|
||||
return True
|
||||
return False
|
||||
|
||||
def render_template(self, template_str: str, context: Dict) -> str:
|
||||
"""Render template with context variables."""
|
||||
result = template_str
|
||||
for key, value in context.items():
|
||||
result = result.replace(f"{{{{{key}}}}}", str(value))
|
||||
return result
|
||||
|
||||
def send_ticket_notification(
|
||||
self,
|
||||
ticket: Ticket,
|
||||
event_type: str,
|
||||
initiator: Optional[User] = None,
|
||||
specialist: Optional[User] = None
|
||||
):
|
||||
"""Send notification for ticket event."""
|
||||
templates = self.get_templates(event_type)
|
||||
|
||||
# Always add default template if no DB template covers this event
|
||||
if not templates:
|
||||
templates = self._get_default_templates(event_type)
|
||||
|
||||
context = {
|
||||
'ticket_id': ticket.id,
|
||||
'ticket_subject': ticket.subject,
|
||||
'ticket_description': (ticket.description or '')[:200],
|
||||
'ticket_status': ticket.status.name if ticket.status else 'N/A',
|
||||
'ticket_priority': ticket.priority.name if ticket.priority else 'N/A',
|
||||
'ticket_url': f'http://localhost:8000/tickets/{ticket.id}',
|
||||
'initiator_name': f"{initiator.first_name} {initiator.last_name}" if initiator else 'N/A',
|
||||
'initiator_email': initiator.email if initiator else 'N/A',
|
||||
'specialist_name': f"{specialist.first_name} {specialist.last_name}" if specialist else 'N/A',
|
||||
'specialist_email': specialist.email if specialist else 'N/A',
|
||||
'current_time': datetime.now().strftime('%Y-%m-%d %H:%M:%S')
|
||||
}
|
||||
|
||||
for template in templates:
|
||||
if not template.is_active:
|
||||
continue
|
||||
|
||||
subject = self.render_template(template.subject_template or '', context)
|
||||
body = self.render_template(template.body_template, context)
|
||||
|
||||
# Send via email
|
||||
if template.channel in ['email', 'both']:
|
||||
self._send_email_notification(template, context, subject, body, initiator, specialist)
|
||||
|
||||
# Send via SMS
|
||||
if template.channel in ['sms', 'both']:
|
||||
self._send_sms_notification(template, context, body, initiator, specialist)
|
||||
|
||||
# Save in-app notification
|
||||
self._save_notification(template, context, subject, body, ticket, initiator, specialist)
|
||||
|
||||
def _send_email_notification(
|
||||
self,
|
||||
template: NotificationTemplate,
|
||||
context: Dict,
|
||||
subject: str,
|
||||
body: str,
|
||||
initiator: Optional[User],
|
||||
specialist: Optional[User]
|
||||
):
|
||||
"""Send email notification via outbox for reliability."""
|
||||
from app.services.email_outbox_service import EmailOutboxService
|
||||
from app.services.ticket_event_service import TicketEventService
|
||||
outbox = EmailOutboxService(self.db)
|
||||
events = TicketEventService(self.db)
|
||||
ticket_id = context.get('ticket_id')
|
||||
|
||||
sent_to = set()
|
||||
|
||||
if template.send_to_initiator and initiator:
|
||||
outbox.enqueue(
|
||||
to_addresses=initiator.email,
|
||||
subject=subject,
|
||||
body_text=body,
|
||||
ticket_id=ticket_id,
|
||||
user_id=initiator.id
|
||||
)
|
||||
events.log(ticket_id, 'email_queued', f'Письмо инициатору: {initiator.email}', initiator.id)
|
||||
sent_to.add(initiator.id)
|
||||
|
||||
if template.send_to_specialist:
|
||||
# Send to ticket's assigned specialist
|
||||
if specialist and specialist.email:
|
||||
outbox.enqueue(
|
||||
to_addresses=specialist.email,
|
||||
subject=subject,
|
||||
body_text=body,
|
||||
ticket_id=ticket_id,
|
||||
user_id=specialist.id
|
||||
)
|
||||
events.log(ticket_id, 'email_queued', f'Письмо специалисту: {specialist.email}', specialist.id)
|
||||
sent_to.add(specialist.id)
|
||||
# Also send to explicitly selected specialists from template
|
||||
if template.specialist_ids:
|
||||
import json as _json
|
||||
try:
|
||||
specialist_ids = _json.loads(template.specialist_ids)
|
||||
except:
|
||||
specialist_ids = []
|
||||
for uid in specialist_ids:
|
||||
if uid in sent_to:
|
||||
continue
|
||||
u = self.db.query(User).filter(User.id == uid, User.is_active == True).first()
|
||||
if u and u.email:
|
||||
outbox.enqueue(
|
||||
to_addresses=u.email,
|
||||
subject=subject,
|
||||
body_text=body,
|
||||
ticket_id=ticket_id,
|
||||
user_id=u.id
|
||||
)
|
||||
events.log(ticket_id, 'email_queued', f'Письмо специалисту: {u.email}', u.id)
|
||||
sent_to.add(u.id)
|
||||
|
||||
# Send to group (support agents, managers, admins)
|
||||
if template.send_to_group:
|
||||
group_roles = ['support_agent', 'admin', 'manager']
|
||||
group_emails = []
|
||||
try:
|
||||
from app.core.platform_client import get_platform_client
|
||||
client = get_platform_client()
|
||||
import asyncio
|
||||
result = asyncio.run(client.get_users(page=1, page_size=1000))
|
||||
for u in result.get("users", []):
|
||||
if u.id not in sent_to and u.email and any(u.has_role(r) for r in group_roles):
|
||||
outbox.enqueue(
|
||||
to_addresses=u.email,
|
||||
subject=subject,
|
||||
body_text=body,
|
||||
ticket_id=ticket_id,
|
||||
user_id=u.id
|
||||
)
|
||||
group_emails.append(u.email)
|
||||
except Exception as e:
|
||||
print(f"Error fetching group users from platform: {e}")
|
||||
if group_emails:
|
||||
events.log(ticket_id, 'email_queued', f'Письмо группе: {", ".join(group_emails)}')
|
||||
|
||||
def _send_sms_notification(
|
||||
self,
|
||||
template: NotificationTemplate,
|
||||
context: Dict,
|
||||
body: str,
|
||||
initiator: Optional[User],
|
||||
specialist: Optional[User]
|
||||
):
|
||||
"""Send SMS notification."""
|
||||
try:
|
||||
sms_client = SMSClient()
|
||||
recipients = []
|
||||
|
||||
if template.send_to_initiator and initiator and initiator.phone:
|
||||
recipients.append(initiator.phone)
|
||||
if template.send_to_specialist and specialist and specialist.phone:
|
||||
recipients.append(specialist.phone)
|
||||
|
||||
for recipient in recipients:
|
||||
sms_client.send_sms(to=recipient, message=body[:160])
|
||||
except Exception as e:
|
||||
print(f"SMS notification error: {e}")
|
||||
|
||||
def _save_notification(
|
||||
self,
|
||||
template: NotificationTemplate,
|
||||
context: Dict,
|
||||
subject: str,
|
||||
body: str,
|
||||
ticket: Ticket,
|
||||
initiator: Optional[User],
|
||||
specialist: Optional[User]
|
||||
):
|
||||
"""Save in-app notification."""
|
||||
users_to_notify = set()
|
||||
if template.send_to_initiator and initiator:
|
||||
users_to_notify.add(initiator.id)
|
||||
if template.send_to_specialist:
|
||||
if specialist:
|
||||
users_to_notify.add(specialist.id)
|
||||
# Also notify explicitly selected specialists
|
||||
if template.specialist_ids:
|
||||
import json as _json
|
||||
try:
|
||||
specialist_ids = _json.loads(template.specialist_ids)
|
||||
except:
|
||||
specialist_ids = []
|
||||
for uid in specialist_ids:
|
||||
users_to_notify.add(uid)
|
||||
|
||||
# Add group members
|
||||
if template.send_to_group:
|
||||
group_roles = ['support_agent', 'admin', 'manager']
|
||||
try:
|
||||
from app.core.platform_client import get_platform_client
|
||||
client = get_platform_client()
|
||||
import asyncio
|
||||
result = asyncio.run(client.get_users(page=1, page_size=1000))
|
||||
for u in result.get("users", []):
|
||||
if any(u.has_role(r) for r in group_roles):
|
||||
users_to_notify.add(u.id)
|
||||
except Exception as e:
|
||||
print(f"Error fetching group users from platform: {e}")
|
||||
|
||||
for user_id in users_to_notify:
|
||||
notification = Notification(
|
||||
user_id=user_id,
|
||||
ticket_id=ticket.id,
|
||||
type='in_app',
|
||||
title=subject[:255],
|
||||
message=body,
|
||||
is_read=0,
|
||||
is_delivered=0
|
||||
)
|
||||
self.db.add(notification)
|
||||
|
||||
self.db.commit()
|
||||
|
||||
def _get_default_templates(self, event_type: str) -> List[NotificationTemplate]:
|
||||
"""Get default templates for event type."""
|
||||
defaults = {
|
||||
'ticket_created': NotificationTemplate(
|
||||
name='Default: Ticket Created',
|
||||
event_type='ticket_created',
|
||||
channel='both',
|
||||
subject_template='Новая заявка #{{ticket_id}}: {{ticket_subject}}',
|
||||
body_template='Создана новая заявка.\n\nТема: {{ticket_subject}}\nПриоритет: {{ticket_priority}}\nИнициатор: {{initiator_name}}\n\nПодробнее: {{ticket_url}}',
|
||||
is_active=True,
|
||||
send_to_initiator=True,
|
||||
send_to_specialist=True
|
||||
),
|
||||
'ticket_assigned': NotificationTemplate(
|
||||
name='Default: Ticket Assigned',
|
||||
event_type='ticket_assigned',
|
||||
channel='both',
|
||||
subject_template='Вам назначена заявка #{{ticket_id}}',
|
||||
body_template='Вам назначена заявка.\n\nТема: {{ticket_subject}}\nПриоритет: {{ticket_priority}}\nИнициатор: {{initiator_name}}\n\nПодробнее: {{ticket_url}}',
|
||||
is_active=True,
|
||||
send_to_initiator=False,
|
||||
send_to_specialist=True
|
||||
),
|
||||
'ticket_updated': NotificationTemplate(
|
||||
name='Default: Ticket Updated',
|
||||
event_type='ticket_updated',
|
||||
channel='email',
|
||||
subject_template='Обновление заявки #{{ticket_id}}',
|
||||
body_template='Заявка обновлена.\n\nТема: {{ticket_subject}}\nСтатус: {{ticket_status}}\n\nПодробнее: {{ticket_url}}',
|
||||
is_active=True,
|
||||
send_to_initiator=True,
|
||||
send_to_specialist=True
|
||||
),
|
||||
'ticket_commented': NotificationTemplate(
|
||||
name='Default: Ticket Commented',
|
||||
event_type='ticket_commented',
|
||||
channel='email',
|
||||
subject_template='Новый ответ в заявке #{{ticket_id}}',
|
||||
body_template='Новый ответ в заявке #{{ticket_id}}.\n\nТема: {{ticket_subject}}\nАвтор: {{initiator_name}}\n\nПодробнее: {{ticket_url}}',
|
||||
is_active=True,
|
||||
send_to_initiator=True,
|
||||
send_to_specialist=True
|
||||
)
|
||||
}
|
||||
|
||||
template = defaults.get(event_type)
|
||||
return [template] if template else []
|
||||
|
||||
# Saved Filters
|
||||
def get_user_filters(self, user_id: int, filter_type: str = 'tickets') -> List[SavedFilter]:
|
||||
"""Get saved filters for user."""
|
||||
return self.db.query(SavedFilter).filter(
|
||||
SavedFilter.user_id == user_id,
|
||||
SavedFilter.filter_type == filter_type
|
||||
).all()
|
||||
|
||||
def create_filter(self, user_id: int, name: str, filter_type: str, filter_config: Dict) -> SavedFilter:
|
||||
"""Create saved filter."""
|
||||
saved_filter = SavedFilter(
|
||||
user_id=user_id,
|
||||
name=name,
|
||||
filter_type=filter_type,
|
||||
filter_config=json.dumps(filter_config)
|
||||
)
|
||||
self.db.add(saved_filter)
|
||||
self.db.commit()
|
||||
self.db.refresh(saved_filter)
|
||||
return saved_filter
|
||||
|
||||
def delete_filter(self, filter_id: int, user_id: int) -> bool:
|
||||
"""Delete saved filter."""
|
||||
saved_filter = self.db.query(SavedFilter).filter(
|
||||
SavedFilter.id == filter_id,
|
||||
SavedFilter.user_id == user_id
|
||||
).first()
|
||||
|
||||
if saved_filter:
|
||||
self.db.delete(saved_filter)
|
||||
self.db.commit()
|
||||
return True
|
||||
return False
|
||||
@@ -0,0 +1,349 @@
|
||||
"""Reference data service."""
|
||||
|
||||
from typing import List, Optional
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.models.status import Status
|
||||
from app.models.priority import Priority
|
||||
from app.models.category import Category
|
||||
from app.models.extra import Company, Location, Department
|
||||
from app.core.exceptions import NotFoundException, ConflictException
|
||||
|
||||
|
||||
class ReferenceService:
|
||||
"""Service for managing reference data."""
|
||||
|
||||
def __init__(self, db: Session):
|
||||
self.db = db
|
||||
|
||||
# Statuses
|
||||
def get_statuses(self) -> List[Status]:
|
||||
"""Get all statuses."""
|
||||
return self.db.query(Status).order_by(Status.name).all()
|
||||
|
||||
def get_status_by_id(self, status_id: int) -> Status:
|
||||
"""Get status by ID."""
|
||||
status = self.db.query(Status).filter(Status.id == status_id).first()
|
||||
if not status:
|
||||
raise NotFoundException(f"Status with id {status_id} not found")
|
||||
return status
|
||||
|
||||
def create_status(self, name: str, is_final: bool = False) -> Status:
|
||||
"""Create new status."""
|
||||
if self.db.query(Status).filter(Status.name == name).first():
|
||||
raise ConflictException(f"Status '{name}' already exists")
|
||||
|
||||
status = Status(name=name, is_final=is_final)
|
||||
self.db.add(status)
|
||||
self.db.commit()
|
||||
self.db.refresh(status)
|
||||
return status
|
||||
|
||||
def update_status(self, status_id: int, name: Optional[str] = None, is_final: Optional[bool] = None) -> Status:
|
||||
"""Update status."""
|
||||
status = self.get_status_by_id(status_id)
|
||||
|
||||
if name is not None:
|
||||
existing = self.db.query(Status).filter(Status.name == name, Status.id != status_id).first()
|
||||
if existing:
|
||||
raise ConflictException(f"Status '{name}' already exists")
|
||||
status.name = name
|
||||
|
||||
if is_final is not None:
|
||||
status.is_final = is_final
|
||||
|
||||
self.db.commit()
|
||||
self.db.refresh(status)
|
||||
return status
|
||||
|
||||
def delete_status(self, status_id: int) -> dict:
|
||||
"""Delete status."""
|
||||
status = self.get_status_by_id(status_id)
|
||||
self.db.delete(status)
|
||||
self.db.commit()
|
||||
return {"message": "Status deleted successfully"}
|
||||
|
||||
# Priorities
|
||||
def get_priorities(self) -> List[Priority]:
|
||||
"""Get all priorities."""
|
||||
return self.db.query(Priority).order_by(Priority.level).all()
|
||||
|
||||
def get_priority_by_id(self, priority_id: int) -> Priority:
|
||||
"""Get priority by ID."""
|
||||
priority = self.db.query(Priority).filter(Priority.id == priority_id).first()
|
||||
if not priority:
|
||||
raise NotFoundException(f"Priority with id {priority_id} not found")
|
||||
return priority
|
||||
|
||||
def create_priority(self, name: str, level: int, default_response_time_minutes: int = 60) -> Priority:
|
||||
"""Create new priority."""
|
||||
if self.db.query(Priority).filter(Priority.name == name).first():
|
||||
raise ConflictException(f"Priority '{name}' already exists")
|
||||
|
||||
priority = Priority(
|
||||
name=name,
|
||||
level=level,
|
||||
default_response_time_minutes=default_response_time_minutes
|
||||
)
|
||||
self.db.add(priority)
|
||||
self.db.commit()
|
||||
self.db.refresh(priority)
|
||||
return priority
|
||||
|
||||
def update_priority(
|
||||
self,
|
||||
priority_id: int,
|
||||
name: Optional[str] = None,
|
||||
level: Optional[int] = None,
|
||||
default_response_time_minutes: Optional[int] = None
|
||||
) -> Priority:
|
||||
"""Update priority."""
|
||||
priority = self.get_priority_by_id(priority_id)
|
||||
|
||||
if name is not None:
|
||||
existing = self.db.query(Priority).filter(Priority.name == name, Priority.id != priority_id).first()
|
||||
if existing:
|
||||
raise ConflictException(f"Priority '{name}' already exists")
|
||||
priority.name = name
|
||||
|
||||
if level is not None:
|
||||
priority.level = level
|
||||
|
||||
if default_response_time_minutes is not None:
|
||||
priority.default_response_time_minutes = default_response_time_minutes
|
||||
|
||||
self.db.commit()
|
||||
self.db.refresh(priority)
|
||||
return priority
|
||||
|
||||
def delete_priority(self, priority_id: int) -> dict:
|
||||
"""Delete priority."""
|
||||
priority = self.get_priority_by_id(priority_id)
|
||||
self.db.delete(priority)
|
||||
self.db.commit()
|
||||
return {"message": "Priority deleted successfully"}
|
||||
|
||||
# Categories
|
||||
def get_categories(self, parent_id: Optional[int] = None) -> List[Category]:
|
||||
"""Get categories, optionally filtered by parent."""
|
||||
query = self.db.query(Category)
|
||||
if parent_id is not None:
|
||||
query = query.filter(Category.parent_id == parent_id)
|
||||
else:
|
||||
query = query.filter(Category.parent_id.is_(None))
|
||||
return query.order_by(Category.name).all()
|
||||
|
||||
def get_all_categories(self) -> List[Category]:
|
||||
"""Get all categories flat."""
|
||||
return self.db.query(Category).order_by(Category.name).all()
|
||||
|
||||
def get_category_by_id(self, category_id: int) -> Category:
|
||||
"""Get category by ID."""
|
||||
category = self.db.query(Category).filter(Category.id == category_id).first()
|
||||
if not category:
|
||||
raise NotFoundException(f"Category with id {category_id} not found")
|
||||
return category
|
||||
|
||||
def create_category(self, name: str, parent_id: Optional[int] = None) -> Category:
|
||||
"""Create new category."""
|
||||
if self.db.query(Category).filter(Category.name == name).first():
|
||||
raise ConflictException(f"Category '{name}' already exists")
|
||||
|
||||
if parent_id is not None:
|
||||
self.get_category_by_id(parent_id)
|
||||
|
||||
category = Category(name=name, parent_id=parent_id)
|
||||
self.db.add(category)
|
||||
self.db.commit()
|
||||
self.db.refresh(category)
|
||||
return category
|
||||
|
||||
def update_category(self, category_id: int, name: Optional[str] = None, parent_id: Optional[int] = None) -> Category:
|
||||
"""Update category."""
|
||||
category = self.get_category_by_id(category_id)
|
||||
|
||||
if name is not None:
|
||||
existing = self.db.query(Category).filter(Category.name == name, Category.id != category_id).first()
|
||||
if existing:
|
||||
raise ConflictException(f"Category '{name}' already exists")
|
||||
category.name = name
|
||||
|
||||
if parent_id is not None:
|
||||
if parent_id == category_id:
|
||||
raise ConflictException("Category cannot be its own parent")
|
||||
self.get_category_by_id(parent_id)
|
||||
category.parent_id = parent_id
|
||||
|
||||
self.db.commit()
|
||||
self.db.refresh(category)
|
||||
return category
|
||||
|
||||
def delete_category(self, category_id: int) -> dict:
|
||||
"""Delete category."""
|
||||
category = self.get_category_by_id(category_id)
|
||||
|
||||
# Update child categories
|
||||
self.db.query(Category).filter(Category.parent_id == category_id).update(
|
||||
{"parent_id": category.parent_id}
|
||||
)
|
||||
|
||||
self.db.delete(category)
|
||||
self.db.commit()
|
||||
return {"message": "Category deleted successfully"}
|
||||
|
||||
# Companies
|
||||
def get_companies(self) -> List[Company]:
|
||||
"""Get all companies."""
|
||||
return self.db.query(Company).order_by(Company.name).all()
|
||||
|
||||
def get_company_by_id(self, company_id: int) -> Company:
|
||||
"""Get company by ID."""
|
||||
company = self.db.query(Company).filter(Company.id == company_id).first()
|
||||
if not company:
|
||||
raise NotFoundException(f"Company with id {company_id} not found")
|
||||
return company
|
||||
|
||||
def create_company(self, name: str, address: Optional[str] = None, phone: Optional[str] = None, website: Optional[str] = None) -> Company:
|
||||
"""Create new company."""
|
||||
if self.db.query(Company).filter(Company.name == name).first():
|
||||
raise ConflictException(f"Company '{name}' already exists")
|
||||
|
||||
company = Company(name=name, address=address, phone=phone, website=website)
|
||||
self.db.add(company)
|
||||
self.db.commit()
|
||||
self.db.refresh(company)
|
||||
return company
|
||||
|
||||
def update_company(
|
||||
self,
|
||||
company_id: int,
|
||||
name: Optional[str] = None,
|
||||
address: Optional[str] = None,
|
||||
phone: Optional[str] = None,
|
||||
website: Optional[str] = None
|
||||
) -> Company:
|
||||
"""Update company."""
|
||||
company = self.get_company_by_id(company_id)
|
||||
|
||||
if name is not None:
|
||||
existing = self.db.query(Company).filter(Company.name == name, Company.id != company_id).first()
|
||||
if existing:
|
||||
raise ConflictException(f"Company '{name}' already exists")
|
||||
company.name = name
|
||||
|
||||
if address is not None:
|
||||
company.address = address
|
||||
if phone is not None:
|
||||
company.phone = phone
|
||||
if website is not None:
|
||||
company.website = website
|
||||
|
||||
self.db.commit()
|
||||
self.db.refresh(company)
|
||||
return company
|
||||
|
||||
def delete_company(self, company_id: int) -> dict:
|
||||
"""Delete company."""
|
||||
company = self.get_company_by_id(company_id)
|
||||
self.db.delete(company)
|
||||
self.db.commit()
|
||||
return {"message": "Company deleted successfully"}
|
||||
|
||||
# Locations
|
||||
def get_locations(self) -> List[Location]:
|
||||
"""Get all locations."""
|
||||
return self.db.query(Location).order_by(Location.name).all()
|
||||
|
||||
def get_location_by_id(self, location_id: int) -> Location:
|
||||
"""Get location by ID."""
|
||||
location = self.db.query(Location).filter(Location.id == location_id).first()
|
||||
if not location:
|
||||
raise NotFoundException(f"Location with id {location_id} not found")
|
||||
return location
|
||||
|
||||
def create_location(self, name: str, address: Optional[str] = None, phone: Optional[str] = None) -> Location:
|
||||
"""Create new location."""
|
||||
if self.db.query(Location).filter(Location.name == name).first():
|
||||
raise ConflictException(f"Location '{name}' already exists")
|
||||
|
||||
location = Location(name=name, address=address, phone=phone)
|
||||
self.db.add(location)
|
||||
self.db.commit()
|
||||
self.db.refresh(location)
|
||||
return location
|
||||
|
||||
def update_location(
|
||||
self,
|
||||
location_id: int,
|
||||
name: Optional[str] = None,
|
||||
address: Optional[str] = None,
|
||||
phone: Optional[str] = None
|
||||
) -> Location:
|
||||
"""Update location."""
|
||||
location = self.get_location_by_id(location_id)
|
||||
|
||||
if name is not None:
|
||||
existing = self.db.query(Location).filter(Location.name == name, Location.id != location_id).first()
|
||||
if existing:
|
||||
raise ConflictException(f"Location '{name}' already exists")
|
||||
location.name = name
|
||||
|
||||
if address is not None:
|
||||
location.address = address
|
||||
if phone is not None:
|
||||
location.phone = phone
|
||||
|
||||
self.db.commit()
|
||||
self.db.refresh(location)
|
||||
return location
|
||||
|
||||
def delete_location(self, location_id: int) -> dict:
|
||||
"""Delete location."""
|
||||
location = self.get_location_by_id(location_id)
|
||||
self.db.delete(location)
|
||||
self.db.commit()
|
||||
return {"message": "Location deleted successfully"}
|
||||
|
||||
# Departments
|
||||
def get_departments(self) -> List[Department]:
|
||||
"""Get all departments."""
|
||||
return self.db.query(Department).order_by(Department.name).all()
|
||||
|
||||
def get_department_by_id(self, department_id: int) -> Department:
|
||||
"""Get department by ID."""
|
||||
department = self.db.query(Department).filter(Department.id == department_id).first()
|
||||
if not department:
|
||||
raise NotFoundException(f"Department with id {department_id} not found")
|
||||
return department
|
||||
|
||||
def create_department(self, name: str) -> Department:
|
||||
"""Create new department."""
|
||||
if self.db.query(Department).filter(Department.name == name).first():
|
||||
raise ConflictException(f"Department '{name}' already exists")
|
||||
|
||||
department = Department(name=name)
|
||||
self.db.add(department)
|
||||
self.db.commit()
|
||||
self.db.refresh(department)
|
||||
return department
|
||||
|
||||
def update_department(self, department_id: int, name: Optional[str] = None) -> Department:
|
||||
"""Update department."""
|
||||
department = self.get_department_by_id(department_id)
|
||||
|
||||
if name is not None:
|
||||
existing = self.db.query(Department).filter(Department.name == name, Department.id != department_id).first()
|
||||
if existing:
|
||||
raise ConflictException(f"Department '{name}' already exists")
|
||||
department.name = name
|
||||
|
||||
self.db.commit()
|
||||
self.db.refresh(department)
|
||||
return department
|
||||
|
||||
def delete_department(self, department_id: int) -> dict:
|
||||
"""Delete department."""
|
||||
department = self.get_department_by_id(department_id)
|
||||
self.db.delete(department)
|
||||
self.db.commit()
|
||||
return {"message": "Department deleted successfully"}
|
||||
@@ -0,0 +1,125 @@
|
||||
"""Settings service."""
|
||||
|
||||
from typing import List, Optional, Dict
|
||||
from sqlalchemy.orm import Session
|
||||
from app.models.setting import SystemSetting
|
||||
from app.core.exceptions import NotFoundException
|
||||
|
||||
|
||||
class SettingsService:
|
||||
"""Settings service for managing system configuration."""
|
||||
|
||||
def __init__(self, db: Session):
|
||||
self.db = db
|
||||
|
||||
def get_settings_by_category(self, category: str) -> List[SystemSetting]:
|
||||
"""Get all settings for a category."""
|
||||
return self.db.query(SystemSetting).filter(
|
||||
SystemSetting.category == category
|
||||
).all()
|
||||
|
||||
def get_setting(self, key: str) -> Optional[SystemSetting]:
|
||||
"""Get a single setting by key."""
|
||||
return self.db.query(SystemSetting).filter(
|
||||
SystemSetting.key == key
|
||||
).first()
|
||||
|
||||
def get_setting_value(self, key: str, default: str = "") -> str:
|
||||
"""Get setting value by key."""
|
||||
setting = self.get_setting(key)
|
||||
return setting.value if setting else default
|
||||
|
||||
def update_setting(self, key: str, value: str) -> SystemSetting:
|
||||
"""Update or create a setting."""
|
||||
setting = self.get_setting(key)
|
||||
|
||||
if setting:
|
||||
setting.value = value
|
||||
else:
|
||||
setting = SystemSetting(key=key, value=value, category=self._get_category(key))
|
||||
self.db.add(setting)
|
||||
|
||||
self.db.commit()
|
||||
self.db.refresh(setting)
|
||||
return setting
|
||||
|
||||
def update_settings_batch(self, settings: Dict[str, str]) -> List[SystemSetting]:
|
||||
"""Update multiple settings at once."""
|
||||
result = []
|
||||
for key, value in settings.items():
|
||||
setting = self.update_setting(key, value)
|
||||
result.append(setting)
|
||||
return result
|
||||
|
||||
def get_email_settings(self) -> Dict[str, str]:
|
||||
"""Get email settings as dictionary."""
|
||||
keys = [
|
||||
'smtp_server', 'smtp_port', 'smtp_username',
|
||||
'smtp_password', 'email_from', 'imap_server',
|
||||
'imap_port', 'use_tls', 'email_fetch_interval',
|
||||
'email_delete_after_fetch'
|
||||
]
|
||||
return {key: self.get_setting_value(key) for key in keys}
|
||||
|
||||
def update_email_settings(self, settings: Dict[str, str]) -> None:
|
||||
"""Update email settings."""
|
||||
for key, value in settings.items():
|
||||
if isinstance(value, bool):
|
||||
value = "true" if value else "false"
|
||||
else:
|
||||
value = str(value)
|
||||
self.update_setting(key, value)
|
||||
|
||||
def get_sms_settings(self) -> Dict[str, str]:
|
||||
"""Get SMS settings as dictionary."""
|
||||
keys = [
|
||||
'twilio_account_sid', 'twilio_auth_token', 'twilio_from_number'
|
||||
]
|
||||
return {key: self.get_setting_value(key) for key in keys}
|
||||
|
||||
def update_sms_settings(self, settings: Dict[str, str]) -> None:
|
||||
"""Update SMS settings."""
|
||||
for key, value in settings.items():
|
||||
self.update_setting(key, value)
|
||||
|
||||
def _get_category(self, key: str) -> str:
|
||||
"""Determine category from key name."""
|
||||
if key.startswith('smtp') or key.startswith('imap') or key.startswith('email'):
|
||||
return 'email'
|
||||
elif key.startswith('twilio') or key.startswith('sms'):
|
||||
return 'sms'
|
||||
else:
|
||||
return 'general'
|
||||
|
||||
def initialize_defaults(self) -> None:
|
||||
"""Initialize default settings if not exists."""
|
||||
defaults = {
|
||||
# Email
|
||||
'smtp_server': ('smtp.gmail.com', 'email'),
|
||||
'smtp_port': ('465', 'email'),
|
||||
'smtp_username': ('', 'email'),
|
||||
'smtp_password': ('', 'email'),
|
||||
'email_from': ('', 'email'),
|
||||
'imap_server': ('imap.gmail.com', 'email'),
|
||||
'imap_port': ('993', 'email'),
|
||||
'use_tls': ('true', 'email'),
|
||||
'email_fetch_interval': ('300', 'email'),
|
||||
'email_delete_after_fetch': ('false', 'email'),
|
||||
# SMS
|
||||
'twilio_account_sid': ('', 'sms'),
|
||||
'twilio_auth_token': ('', 'sms'),
|
||||
'twilio_from_number': ('', 'sms'),
|
||||
}
|
||||
|
||||
for key, (value, category) in defaults.items():
|
||||
existing = self.get_setting(key)
|
||||
if not existing:
|
||||
setting = SystemSetting(
|
||||
key=key,
|
||||
value=value,
|
||||
category=category,
|
||||
is_secret='password' in key or 'token' in key
|
||||
)
|
||||
self.db.add(setting)
|
||||
|
||||
self.db.commit()
|
||||
@@ -0,0 +1,43 @@
|
||||
"""Ticket event service for system audit log."""
|
||||
|
||||
from typing import List, Optional
|
||||
from sqlalchemy.orm import Session
|
||||
from app.models.ticket_event import TicketEvent
|
||||
from app.core.logging import ticket_logger
|
||||
|
||||
|
||||
class TicketEventService:
|
||||
"""Manages ticket system events."""
|
||||
|
||||
def __init__(self, db: Session):
|
||||
self.db = db
|
||||
|
||||
def log(
|
||||
self,
|
||||
ticket_id: int,
|
||||
event_type: str,
|
||||
message: str,
|
||||
user_id: Optional[int] = None,
|
||||
extra_data: Optional[str] = None
|
||||
) -> TicketEvent:
|
||||
"""Log a ticket event."""
|
||||
event = TicketEvent(
|
||||
ticket_id=ticket_id,
|
||||
event_type=event_type,
|
||||
message=message,
|
||||
user_id=user_id,
|
||||
extra_data=extra_data
|
||||
)
|
||||
self.db.add(event)
|
||||
self.db.commit()
|
||||
ticket_logger.debug(f"Ticket event: [{ticket_id}] {event_type}: {message}")
|
||||
return event
|
||||
|
||||
def get_ticket_events(self, ticket_id: int) -> List[TicketEvent]:
|
||||
"""Get all events for a ticket."""
|
||||
return (
|
||||
self.db.query(TicketEvent)
|
||||
.filter(TicketEvent.ticket_id == ticket_id)
|
||||
.order_by(TicketEvent.created_at.asc())
|
||||
.all()
|
||||
)
|
||||
@@ -0,0 +1,217 @@
|
||||
"""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 app.models.ticket import Ticket
|
||||
from app.models.comment import Comment
|
||||
from app.models.user import User
|
||||
from app.models.priority import Priority
|
||||
from app.models.status import Status
|
||||
from app.models.category import Category
|
||||
from app.models.extra import Company, Location
|
||||
from app.schemas.ticket import TicketCreate, TicketUpdate, TicketResponse
|
||||
from app.core.exceptions import NotFoundException, ValidationException
|
||||
from app.core.logging import ticket_logger
|
||||
from 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 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 app.core.logging import logger
|
||||
try:
|
||||
from 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)
|
||||
@@ -0,0 +1,88 @@
|
||||
"""User service - platform integration."""
|
||||
|
||||
from typing import List, Optional, Tuple
|
||||
from sqlalchemy.orm import Session
|
||||
from datetime import datetime
|
||||
|
||||
from app.models.user import User
|
||||
from app.models.extra import UserDepartment
|
||||
from app.core.platform_client import PlatformUser, get_platform_client
|
||||
|
||||
|
||||
class UserService:
|
||||
"""User service - delegates to platform for user data."""
|
||||
|
||||
def __init__(self, db: Session):
|
||||
self.db = db
|
||||
|
||||
def get_user_by_id(self, user_id: int) -> User:
|
||||
"""Get local user cache by ID."""
|
||||
user = self.db.query(User).filter(User.id == user_id).first()
|
||||
if not user:
|
||||
raise Exception(f"User with id {user_id} not found in local cache")
|
||||
return user
|
||||
|
||||
def get_or_create_user_cache(self, user_id: int, email: str = "", first_name: str = "", last_name: str = "") -> User:
|
||||
"""Get or create local user cache entry."""
|
||||
user = self.db.query(User).filter(User.id == user_id).first()
|
||||
if not user:
|
||||
user = User(
|
||||
id=user_id,
|
||||
email=email,
|
||||
first_name=first_name,
|
||||
last_name=last_name,
|
||||
is_active=True,
|
||||
synced_at=datetime.utcnow(),
|
||||
)
|
||||
self.db.add(user)
|
||||
self.db.commit()
|
||||
self.db.refresh(user)
|
||||
return user
|
||||
|
||||
def sync_user_from_platform(self, platform_user: PlatformUser) -> User:
|
||||
"""Sync platform user data to local cache."""
|
||||
user = self.db.query(User).filter(User.id == platform_user.id).first()
|
||||
if not user:
|
||||
user = User(id=platform_user.id)
|
||||
self.db.add(user)
|
||||
|
||||
user.email = platform_user.email
|
||||
user.first_name = platform_user.first_name
|
||||
user.last_name = platform_user.last_name
|
||||
user.is_active = platform_user.is_active
|
||||
user.synced_at = datetime.utcnow()
|
||||
|
||||
self.db.commit()
|
||||
self.db.refresh(user)
|
||||
return user
|
||||
|
||||
def get_user_departments(self, user_id: int) -> List[UserDepartment]:
|
||||
"""Get user departments (local)."""
|
||||
return self.db.query(UserDepartment).filter(UserDepartment.user_id == user_id).all()
|
||||
|
||||
def assign_department(self, user_id: int, department_id: int) -> UserDepartment:
|
||||
"""Assign user to department (local)."""
|
||||
existing = self.db.query(UserDepartment).filter(
|
||||
UserDepartment.user_id == user_id,
|
||||
UserDepartment.department_id == department_id,
|
||||
).first()
|
||||
if existing:
|
||||
return existing
|
||||
|
||||
ud = UserDepartment(user_id=user_id, department_id=department_id)
|
||||
self.db.add(ud)
|
||||
self.db.commit()
|
||||
self.db.refresh(ud)
|
||||
return ud
|
||||
|
||||
def remove_department(self, user_id: int, department_id: int) -> bool:
|
||||
"""Remove user from department (local)."""
|
||||
ud = self.db.query(UserDepartment).filter(
|
||||
UserDepartment.user_id == user_id,
|
||||
UserDepartment.department_id == department_id,
|
||||
).first()
|
||||
if ud:
|
||||
self.db.delete(ud)
|
||||
self.db.commit()
|
||||
return True
|
||||
return False
|
||||
Reference in New Issue
Block a user