"""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