TT-003: complete request-module integration into modular platform
- 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
This commit is contained in:
@@ -0,0 +1,3 @@
|
||||
"""App package."""
|
||||
|
||||
__version__ = "1.0.0"
|
||||
@@ -0,0 +1,5 @@
|
||||
"""Core module for API."""
|
||||
|
||||
from request_app.api.v1 import routes
|
||||
|
||||
__all__ = ["routes"]
|
||||
@@ -0,0 +1,5 @@
|
||||
"""API v1 package."""
|
||||
|
||||
from request_app.api.v1 import routes
|
||||
|
||||
__all__ = ["routes"]
|
||||
@@ -0,0 +1,5 @@
|
||||
"""API routes package."""
|
||||
|
||||
from request_app.api.v1.routes import tickets, users, auth, health, reference, notifications, emails, settings, notification_templates
|
||||
|
||||
__all__ = ["tickets", "users", "auth", "health", "reference", "notifications", "emails", "settings", "notification_templates"]
|
||||
@@ -0,0 +1,69 @@
|
||||
"""Auth routes."""
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from request_app.core.database import get_db
|
||||
from request_app.core.auth import get_current_user
|
||||
from request_app.core.security import verify_password, create_local_token
|
||||
from request_app.models.user import User
|
||||
|
||||
router = APIRouter(tags=["Authentication"])
|
||||
|
||||
|
||||
def _get_user_roles(user: User) -> list:
|
||||
"""Get user role names."""
|
||||
return [ur.role.name for ur in user.user_roles if ur.role]
|
||||
|
||||
|
||||
@router.post("/login")
|
||||
async def login(data: dict, db: Session = Depends(get_db)):
|
||||
"""Local login with email/password (standalone mode)."""
|
||||
email = data.get("email")
|
||||
password = data.get("password")
|
||||
|
||||
if not email or not password:
|
||||
raise HTTPException(status_code=400, detail="Email and password required")
|
||||
|
||||
user = db.query(User).filter(User.email == email).first()
|
||||
if not user:
|
||||
raise HTTPException(status_code=401, detail="Invalid email or password")
|
||||
|
||||
if not user.is_active:
|
||||
raise HTTPException(status_code=403, detail="User is deactivated")
|
||||
|
||||
# For local users - verify password
|
||||
# For platform users - they should use platform login
|
||||
if user.source == "platform":
|
||||
raise HTTPException(status_code=400, detail="Platform users must login via platform")
|
||||
|
||||
if not verify_password(password, user.password_hash or ""):
|
||||
raise HTTPException(status_code=401, detail="Invalid email or password")
|
||||
|
||||
token = create_local_token(user.id, user.email)
|
||||
return {
|
||||
"access_token": token,
|
||||
"token_type": "bearer",
|
||||
"user": {
|
||||
"id": user.id,
|
||||
"email": user.email,
|
||||
"first_name": user.first_name,
|
||||
"last_name": user.last_name,
|
||||
"is_active": user.is_active,
|
||||
"roles": _get_user_roles(user),
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@router.get("/me")
|
||||
async def get_me(current_user: User = Depends(get_current_user)):
|
||||
"""Get current authenticated user."""
|
||||
return {
|
||||
"id": current_user.id,
|
||||
"email": current_user.email,
|
||||
"first_name": current_user.first_name,
|
||||
"last_name": current_user.last_name,
|
||||
"is_active": current_user.is_active,
|
||||
"source": current_user.source,
|
||||
"roles": _get_user_roles(current_user),
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
"""Email message routes."""
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from sqlalchemy.orm import Session
|
||||
from typing import List
|
||||
|
||||
from request_app.core.database import get_db
|
||||
from request_app.core.auth import get_current_user_id
|
||||
from request_app.core.exceptions import NotFoundException
|
||||
from request_app.schemas.email import (
|
||||
EmailMessageResponse,
|
||||
EmailMessageListResponse,
|
||||
SendEmailRequest,
|
||||
ForwardEmailRequest
|
||||
)
|
||||
from request_app.services.email_message_service import EmailMessageService
|
||||
|
||||
router = APIRouter(prefix="/tickets/{ticket_id}/emails", tags=["Emails"])
|
||||
|
||||
|
||||
@router.get("", response_model=List[EmailMessageResponse])
|
||||
async def get_ticket_emails(
|
||||
ticket_id: int,
|
||||
token: str = Depends(get_current_user_id),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""Get all email messages for a ticket."""
|
||||
service = EmailMessageService(db)
|
||||
try:
|
||||
return service.get_ticket_emails(ticket_id)
|
||||
except NotFoundException as e:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))
|
||||
|
||||
|
||||
@router.get("/{email_id}", response_model=EmailMessageResponse)
|
||||
async def get_email(
|
||||
ticket_id: int,
|
||||
email_id: int,
|
||||
token: str = Depends(get_current_user_id),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""Get email message by ID."""
|
||||
service = EmailMessageService(db)
|
||||
try:
|
||||
email = service.get_email_by_id(email_id)
|
||||
if email.ticket_id != ticket_id:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Email not found in this ticket")
|
||||
return email
|
||||
except NotFoundException as e:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))
|
||||
|
||||
|
||||
@router.post("/reply", response_model=EmailMessageResponse, status_code=status.HTTP_201_CREATED)
|
||||
async def send_reply(
|
||||
ticket_id: int,
|
||||
email_data: SendEmailRequest,
|
||||
user_id: int = Depends(get_current_user_id),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""Send a reply email."""
|
||||
service = EmailMessageService(db)
|
||||
try:
|
||||
return service.send_reply(
|
||||
ticket_id=ticket_id,
|
||||
user_id=user_id,
|
||||
to_addresses=email_data.to_addresses,
|
||||
subject=email_data.subject,
|
||||
body_text=email_data.body_text,
|
||||
body_html=email_data.body_html,
|
||||
in_reply_to=email_data.in_reply_to,
|
||||
cc_addresses=email_data.cc_addresses
|
||||
)
|
||||
except NotFoundException as e:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e))
|
||||
|
||||
|
||||
@router.post("/{email_id}/forward", response_model=EmailMessageResponse, status_code=status.HTTP_201_CREATED)
|
||||
async def forward_email(
|
||||
ticket_id: int,
|
||||
email_id: int,
|
||||
forward_data: ForwardEmailRequest,
|
||||
user_id: int = Depends(get_current_user_id),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""Forward an email to new recipients."""
|
||||
service = EmailMessageService(db)
|
||||
try:
|
||||
return service.forward_email(
|
||||
email_id=email_id,
|
||||
user_id=user_id,
|
||||
to_addresses=forward_data.to_addresses,
|
||||
cc_addresses=forward_data.cc_addresses,
|
||||
add_message=forward_data.add_message
|
||||
)
|
||||
except NotFoundException as e:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=status.HTTP_500_INTERNAL_SERVER_ERROR, detail=str(e))
|
||||
|
||||
|
||||
@router.put("/{email_id}/read", response_model=EmailMessageResponse)
|
||||
async def mark_as_read(
|
||||
ticket_id: int,
|
||||
email_id: int,
|
||||
token: str = Depends(get_current_user_id),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""Mark email as read."""
|
||||
service = EmailMessageService(db)
|
||||
try:
|
||||
return service.mark_as_read(email_id)
|
||||
except NotFoundException as e:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))
|
||||
@@ -0,0 +1,36 @@
|
||||
"""Health check routes."""
|
||||
|
||||
from fastapi import APIRouter, Depends
|
||||
from sqlalchemy.orm import Session
|
||||
from sqlalchemy import text
|
||||
from request_app.core.database import get_db
|
||||
|
||||
router = APIRouter(tags=["Health"])
|
||||
|
||||
|
||||
@router.get("/health")
|
||||
async def health_check():
|
||||
"""Health check endpoint."""
|
||||
return {
|
||||
"status": "healthy",
|
||||
"service": "Service Request System",
|
||||
"version": "1.0.0"
|
||||
}
|
||||
|
||||
|
||||
@router.get("/health/db")
|
||||
async def health_check_db(db: Session = Depends(get_db)):
|
||||
"""Check database connectivity."""
|
||||
try:
|
||||
db.execute(text("SELECT 1"))
|
||||
return {
|
||||
"status": "healthy",
|
||||
"database": "PostgreSQL",
|
||||
"message": "Database connection successful"
|
||||
}
|
||||
except Exception as e:
|
||||
return {
|
||||
"status": "unhealthy",
|
||||
"database": "PostgreSQL",
|
||||
"error": str(e)
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
"""Notification templates and saved filters routes."""
|
||||
|
||||
import json
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from sqlalchemy.orm import Session
|
||||
from typing import List, Optional, Dict
|
||||
|
||||
from request_app.core.database import get_db
|
||||
from request_app.core.auth import get_current_user_id
|
||||
from request_app.services.notification_service_extended import NotificationServiceExtended
|
||||
from request_app.models.notification_template import NotificationTemplate, SavedFilter
|
||||
|
||||
router = APIRouter(prefix="/notifications", tags=["Notifications"])
|
||||
|
||||
|
||||
# Templates
|
||||
@router.get("/templates", response_model=List[dict])
|
||||
async def get_templates(
|
||||
event_type: Optional[str] = None,
|
||||
token: str = Depends(get_current_user_id),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""Get notification templates."""
|
||||
service = NotificationServiceExtended(db)
|
||||
templates = service.get_templates(event_type)
|
||||
result = []
|
||||
for t in templates:
|
||||
specialist_ids = []
|
||||
if t.specialist_ids:
|
||||
try:
|
||||
specialist_ids = json.loads(t.specialist_ids)
|
||||
except:
|
||||
pass
|
||||
result.append({
|
||||
"id": t.id,
|
||||
"name": t.name,
|
||||
"event_type": t.event_type,
|
||||
"channel": t.channel,
|
||||
"subject_template": t.subject_template,
|
||||
"body_template": t.body_template,
|
||||
"is_active": t.is_active,
|
||||
"send_to_initiator": t.send_to_initiator,
|
||||
"send_to_specialist": t.send_to_specialist,
|
||||
"send_to_group": t.send_to_group,
|
||||
"department_id": t.department_id,
|
||||
"specialist_ids": specialist_ids
|
||||
})
|
||||
return result
|
||||
|
||||
|
||||
@router.post("/templates", status_code=status.HTTP_201_CREATED)
|
||||
async def create_template(
|
||||
data: Dict,
|
||||
token: str = Depends(get_current_user_id),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""Create notification template."""
|
||||
service = NotificationServiceExtended(db)
|
||||
try:
|
||||
template = service.create_template(**data)
|
||||
return {"id": template.id, "message": "Template created"}
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
|
||||
|
||||
|
||||
@router.put("/templates/{template_id}")
|
||||
async def update_template(
|
||||
template_id: int,
|
||||
data: Dict,
|
||||
token: str = Depends(get_current_user_id),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""Update notification template."""
|
||||
service = NotificationServiceExtended(db)
|
||||
try:
|
||||
template = service.update_template(template_id, **data)
|
||||
return {"id": template.id, "message": "Template updated"}
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))
|
||||
|
||||
|
||||
@router.delete("/templates/{template_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
async def delete_template(
|
||||
template_id: int,
|
||||
token: str = Depends(get_current_user_id),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""Delete notification template."""
|
||||
service = NotificationServiceExtended(db)
|
||||
if not service.delete_template(template_id):
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Template not found")
|
||||
|
||||
|
||||
# Saved Filters
|
||||
@router.get("/filters")
|
||||
async def get_saved_filters(
|
||||
filter_type: str = "tickets",
|
||||
token: str = Depends(get_current_user_id),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""Get saved filters for current user."""
|
||||
service = NotificationServiceExtended(db)
|
||||
filters = service.get_user_filters(token, filter_type)
|
||||
result = []
|
||||
for f in filters:
|
||||
config = f.filter_config
|
||||
# Parse JSON string if needed
|
||||
if isinstance(config, str):
|
||||
try:
|
||||
config = json.loads(config)
|
||||
except:
|
||||
config = {}
|
||||
result.append({
|
||||
"id": f.id,
|
||||
"name": f.name,
|
||||
"filter_type": f.filter_type,
|
||||
"filter_config": config
|
||||
})
|
||||
return result
|
||||
|
||||
|
||||
@router.post("/filters", status_code=status.HTTP_201_CREATED)
|
||||
async def create_saved_filter(
|
||||
data: Dict,
|
||||
token: str = Depends(get_current_user_id),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""Create saved filter."""
|
||||
service = NotificationServiceExtended(db)
|
||||
try:
|
||||
saved_filter = service.create_filter(
|
||||
user_id=token,
|
||||
name=data.get('name', 'Unnamed'),
|
||||
filter_type=data.get('filter_type', 'tickets'),
|
||||
filter_config=data.get('filter_config', {})
|
||||
)
|
||||
return {"id": saved_filter.id, "message": "Filter saved"}
|
||||
except Exception as e:
|
||||
raise HTTPException(status_code=status.HTTP_400_BAD_REQUEST, detail=str(e))
|
||||
|
||||
|
||||
@router.delete("/filters/{filter_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
async def delete_saved_filter(
|
||||
filter_id: int,
|
||||
token: str = Depends(get_current_user_id),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""Delete saved filter."""
|
||||
service = NotificationServiceExtended(db)
|
||||
if not service.delete_filter(filter_id, token):
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Filter not found")
|
||||
@@ -0,0 +1,76 @@
|
||||
"""Notification routes."""
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, status, Query
|
||||
from sqlalchemy.orm import Session
|
||||
from typing import List, Optional
|
||||
|
||||
from request_app.core.database import get_db
|
||||
from request_app.core.auth import get_current_user_id
|
||||
from request_app.schemas.reference import NotificationResponse, NotificationListResponse
|
||||
from request_app.services.notification_service import NotificationService
|
||||
|
||||
router = APIRouter(prefix="/notifications", tags=["Notifications"])
|
||||
|
||||
|
||||
@router.get("", response_model=NotificationListResponse)
|
||||
async def get_notifications(
|
||||
is_read: Optional[int] = Query(None, description="Filter by read status (0 or 1)"),
|
||||
token: str = Depends(get_current_user_id),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""Get current user's notifications."""
|
||||
service = NotificationService(db)
|
||||
|
||||
notifications = service.get_user_notifications(token, is_read)
|
||||
|
||||
# Count unread
|
||||
unread_count = sum(1 for n in notifications if n.is_read == 0)
|
||||
|
||||
return NotificationListResponse(
|
||||
notifications=notifications,
|
||||
total=len(notifications),
|
||||
unread_count=unread_count
|
||||
)
|
||||
|
||||
|
||||
@router.put("/{notification_id}/read", response_model=NotificationResponse)
|
||||
async def mark_as_read(
|
||||
notification_id: int,
|
||||
token: str = Depends(get_current_user_id),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""Mark notification as read."""
|
||||
service = NotificationService(db)
|
||||
|
||||
try:
|
||||
return service.mark_as_read(notification_id, token)
|
||||
except ValueError as e:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))
|
||||
|
||||
|
||||
@router.put("/read-all")
|
||||
async def mark_all_as_read(
|
||||
token: str = Depends(get_current_user_id),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""Mark all notifications as read."""
|
||||
service = NotificationService(db)
|
||||
updated = service.mark_all_as_read(token)
|
||||
|
||||
return {"message": f"Marked {updated} notifications as read"}
|
||||
|
||||
|
||||
@router.delete("/{notification_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
async def delete_notification(
|
||||
notification_id: int,
|
||||
token: str = Depends(get_current_user_id),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""Delete notification."""
|
||||
service = NotificationService(db)
|
||||
|
||||
if not service.delete_notification(notification_id, token):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail="Notification not found"
|
||||
)
|
||||
@@ -0,0 +1,410 @@
|
||||
"""Reference data routes."""
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, status, Query
|
||||
from sqlalchemy.orm import Session
|
||||
from typing import List, Optional
|
||||
|
||||
from request_app.core.database import get_db
|
||||
from request_app.core.auth import get_current_user_id
|
||||
from request_app.core.exceptions import NotFoundException, ConflictException
|
||||
from request_app.schemas.reference import (
|
||||
StatusCreate, StatusResponse,
|
||||
PriorityCreate, PriorityResponse,
|
||||
CategoryCreate, CategoryResponse,
|
||||
CompanyCreate, CompanyResponse,
|
||||
LocationCreate, LocationResponse,
|
||||
DepartmentCreate, DepartmentResponse
|
||||
)
|
||||
from request_app.services.reference_service import ReferenceService
|
||||
|
||||
router = APIRouter(prefix="/reference", tags=["Reference Data"])
|
||||
|
||||
|
||||
# Roles (module declares its available roles for platform import)
|
||||
@router.get("/roles")
|
||||
async def get_roles():
|
||||
"""Return module's available roles. Called by platform during sync."""
|
||||
return [
|
||||
{"name": "admin", "description": "Administrator with full access"},
|
||||
{"name": "support_agent", "description": "Support agent - create and update tickets"},
|
||||
{"name": "manager", "description": "Manager - view all tickets, create teams"},
|
||||
{"name": "customer", "description": "Customer - read-only, create tickets"},
|
||||
]
|
||||
|
||||
|
||||
# Statuses
|
||||
@router.get("/statuses", response_model=List[StatusResponse])
|
||||
async def get_statuses(
|
||||
token: str = Depends(get_current_user_id),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""Get all statuses."""
|
||||
service = ReferenceService(db)
|
||||
return service.get_statuses()
|
||||
|
||||
|
||||
@router.post("/statuses", response_model=StatusResponse, status_code=status.HTTP_201_CREATED)
|
||||
async def create_status(
|
||||
status_data: StatusCreate,
|
||||
token: str = Depends(get_current_user_id),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""Create new status."""
|
||||
service = ReferenceService(db)
|
||||
try:
|
||||
return service.create_status(status_data.name, status_data.is_final)
|
||||
except ConflictException as e:
|
||||
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(e))
|
||||
|
||||
|
||||
@router.put("/statuses/{status_id}", response_model=StatusResponse)
|
||||
async def update_status(
|
||||
status_id: int,
|
||||
status_data: StatusCreate,
|
||||
token: str = Depends(get_current_user_id),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""Update status."""
|
||||
service = ReferenceService(db)
|
||||
try:
|
||||
return service.update_status(status_id, status_data.name, status_data.is_final)
|
||||
except NotFoundException as e:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))
|
||||
except ConflictException as e:
|
||||
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(e))
|
||||
|
||||
|
||||
@router.delete("/statuses/{status_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
async def delete_status(
|
||||
status_id: int,
|
||||
token: str = Depends(get_current_user_id),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""Delete status."""
|
||||
service = ReferenceService(db)
|
||||
try:
|
||||
service.delete_status(status_id)
|
||||
except NotFoundException as e:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))
|
||||
|
||||
|
||||
# Priorities
|
||||
@router.get("/priorities", response_model=List[PriorityResponse])
|
||||
async def get_priorities(
|
||||
token: str = Depends(get_current_user_id),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""Get all priorities."""
|
||||
service = ReferenceService(db)
|
||||
return service.get_priorities()
|
||||
|
||||
|
||||
@router.post("/priorities", response_model=PriorityResponse, status_code=status.HTTP_201_CREATED)
|
||||
async def create_priority(
|
||||
priority_data: PriorityCreate,
|
||||
token: str = Depends(get_current_user_id),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""Create new priority."""
|
||||
service = ReferenceService(db)
|
||||
try:
|
||||
return service.create_priority(
|
||||
priority_data.name,
|
||||
priority_data.level,
|
||||
priority_data.default_response_time_minutes
|
||||
)
|
||||
except ConflictException as e:
|
||||
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(e))
|
||||
|
||||
|
||||
@router.put("/priorities/{priority_id}", response_model=PriorityResponse)
|
||||
async def update_priority(
|
||||
priority_id: int,
|
||||
priority_data: PriorityCreate,
|
||||
token: str = Depends(get_current_user_id),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""Update priority."""
|
||||
service = ReferenceService(db)
|
||||
try:
|
||||
return service.update_priority(
|
||||
priority_id,
|
||||
priority_data.name,
|
||||
priority_data.level,
|
||||
priority_data.default_response_time_minutes
|
||||
)
|
||||
except NotFoundException as e:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))
|
||||
except ConflictException as e:
|
||||
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(e))
|
||||
|
||||
|
||||
@router.delete("/priorities/{priority_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
async def delete_priority(
|
||||
priority_id: int,
|
||||
token: str = Depends(get_current_user_id),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""Delete priority."""
|
||||
service = ReferenceService(db)
|
||||
try:
|
||||
service.delete_priority(priority_id)
|
||||
except NotFoundException as e:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))
|
||||
|
||||
|
||||
# Categories
|
||||
@router.get("/categories", response_model=List[CategoryResponse])
|
||||
async def get_categories(
|
||||
parent_id: Optional[int] = Query(None),
|
||||
token: str = Depends(get_current_user_id),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""Get categories, optionally filtered by parent."""
|
||||
service = ReferenceService(db)
|
||||
return service.get_categories(parent_id)
|
||||
|
||||
|
||||
@router.get("/categories/all", response_model=List[CategoryResponse])
|
||||
async def get_all_categories(
|
||||
token: str = Depends(get_current_user_id),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""Get all categories flat."""
|
||||
service = ReferenceService(db)
|
||||
return service.get_all_categories()
|
||||
|
||||
|
||||
@router.post("/categories", response_model=CategoryResponse, status_code=status.HTTP_201_CREATED)
|
||||
async def create_category(
|
||||
category_data: CategoryCreate,
|
||||
token: str = Depends(get_current_user_id),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""Create new category."""
|
||||
service = ReferenceService(db)
|
||||
try:
|
||||
return service.create_category(category_data.name, category_data.parent_id)
|
||||
except ConflictException as e:
|
||||
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(e))
|
||||
except NotFoundException as e:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))
|
||||
|
||||
|
||||
@router.put("/categories/{category_id}", response_model=CategoryResponse)
|
||||
async def update_category(
|
||||
category_id: int,
|
||||
category_data: CategoryCreate,
|
||||
token: str = Depends(get_current_user_id),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""Update category."""
|
||||
service = ReferenceService(db)
|
||||
try:
|
||||
return service.update_category(category_id, category_data.name, category_data.parent_id)
|
||||
except NotFoundException as e:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))
|
||||
except ConflictException as e:
|
||||
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(e))
|
||||
|
||||
|
||||
@router.delete("/categories/{category_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
async def delete_category(
|
||||
category_id: int,
|
||||
token: str = Depends(get_current_user_id),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""Delete category."""
|
||||
service = ReferenceService(db)
|
||||
try:
|
||||
service.delete_category(category_id)
|
||||
except NotFoundException as e:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))
|
||||
|
||||
|
||||
# Companies
|
||||
@router.get("/companies", response_model=List[CompanyResponse])
|
||||
async def get_companies(
|
||||
token: str = Depends(get_current_user_id),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""Get all companies."""
|
||||
service = ReferenceService(db)
|
||||
return service.get_companies()
|
||||
|
||||
|
||||
@router.post("/companies", response_model=CompanyResponse, status_code=status.HTTP_201_CREATED)
|
||||
async def create_company(
|
||||
company_data: CompanyCreate,
|
||||
token: str = Depends(get_current_user_id),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""Create new company."""
|
||||
service = ReferenceService(db)
|
||||
try:
|
||||
return service.create_company(
|
||||
company_data.name,
|
||||
company_data.address,
|
||||
company_data.phone,
|
||||
company_data.website
|
||||
)
|
||||
except ConflictException as e:
|
||||
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(e))
|
||||
|
||||
|
||||
@router.put("/companies/{company_id}", response_model=CompanyResponse)
|
||||
async def update_company(
|
||||
company_id: int,
|
||||
company_data: CompanyCreate,
|
||||
token: str = Depends(get_current_user_id),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""Update company."""
|
||||
service = ReferenceService(db)
|
||||
try:
|
||||
return service.update_company(
|
||||
company_id,
|
||||
company_data.name,
|
||||
company_data.address,
|
||||
company_data.phone,
|
||||
company_data.website
|
||||
)
|
||||
except NotFoundException as e:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))
|
||||
except ConflictException as e:
|
||||
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(e))
|
||||
|
||||
|
||||
@router.delete("/companies/{company_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
async def delete_company(
|
||||
company_id: int,
|
||||
token: str = Depends(get_current_user_id),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""Delete company."""
|
||||
service = ReferenceService(db)
|
||||
try:
|
||||
service.delete_company(company_id)
|
||||
except NotFoundException as e:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))
|
||||
|
||||
|
||||
# Locations
|
||||
@router.get("/locations", response_model=List[LocationResponse])
|
||||
async def get_locations(
|
||||
token: str = Depends(get_current_user_id),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""Get all locations."""
|
||||
service = ReferenceService(db)
|
||||
return service.get_locations()
|
||||
|
||||
|
||||
@router.post("/locations", response_model=LocationResponse, status_code=status.HTTP_201_CREATED)
|
||||
async def create_location(
|
||||
location_data: LocationCreate,
|
||||
token: str = Depends(get_current_user_id),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""Create new location."""
|
||||
service = ReferenceService(db)
|
||||
try:
|
||||
return service.create_location(
|
||||
location_data.name,
|
||||
location_data.address,
|
||||
location_data.phone
|
||||
)
|
||||
except ConflictException as e:
|
||||
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(e))
|
||||
|
||||
|
||||
@router.put("/locations/{location_id}", response_model=LocationResponse)
|
||||
async def update_location(
|
||||
location_id: int,
|
||||
location_data: LocationCreate,
|
||||
token: str = Depends(get_current_user_id),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""Update location."""
|
||||
service = ReferenceService(db)
|
||||
try:
|
||||
return service.update_location(
|
||||
location_id,
|
||||
location_data.name,
|
||||
location_data.address,
|
||||
location_data.phone
|
||||
)
|
||||
except NotFoundException as e:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))
|
||||
except ConflictException as e:
|
||||
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(e))
|
||||
|
||||
|
||||
@router.delete("/locations/{location_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
async def delete_location(
|
||||
location_id: int,
|
||||
token: str = Depends(get_current_user_id),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""Delete location."""
|
||||
service = ReferenceService(db)
|
||||
try:
|
||||
service.delete_location(location_id)
|
||||
except NotFoundException as e:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))
|
||||
|
||||
|
||||
# Departments
|
||||
@router.get("/departments", response_model=List[DepartmentResponse])
|
||||
async def get_departments(
|
||||
token: str = Depends(get_current_user_id),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""Get all departments."""
|
||||
service = ReferenceService(db)
|
||||
return service.get_departments()
|
||||
|
||||
|
||||
@router.post("/departments", response_model=DepartmentResponse, status_code=status.HTTP_201_CREATED)
|
||||
async def create_department(
|
||||
department_data: DepartmentCreate,
|
||||
token: str = Depends(get_current_user_id),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""Create new department."""
|
||||
service = ReferenceService(db)
|
||||
try:
|
||||
return service.create_department(department_data.name)
|
||||
except ConflictException as e:
|
||||
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(e))
|
||||
|
||||
|
||||
@router.put("/departments/{department_id}", response_model=DepartmentResponse)
|
||||
async def update_department(
|
||||
department_id: int,
|
||||
department_data: DepartmentCreate,
|
||||
token: str = Depends(get_current_user_id),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""Update department."""
|
||||
service = ReferenceService(db)
|
||||
try:
|
||||
return service.update_department(department_id, department_data.name)
|
||||
except NotFoundException as e:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))
|
||||
except ConflictException as e:
|
||||
raise HTTPException(status_code=status.HTTP_409_CONFLICT, detail=str(e))
|
||||
|
||||
|
||||
@router.delete("/departments/{department_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
async def delete_department(
|
||||
department_id: int,
|
||||
token: str = Depends(get_current_user_id),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""Delete department."""
|
||||
service = ReferenceService(db)
|
||||
try:
|
||||
service.delete_department(department_id)
|
||||
except NotFoundException as e:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail=str(e))
|
||||
@@ -0,0 +1,368 @@
|
||||
"""Settings routes."""
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from sqlalchemy.orm import Session
|
||||
from typing import Dict
|
||||
|
||||
from request_app.core.database import get_db
|
||||
from request_app.core.auth import get_current_user_id
|
||||
from request_app.core.logging import logger
|
||||
from request_app.services.settings_service import SettingsService
|
||||
from request_app.schemas.settings import (
|
||||
SettingResponse, SettingUpdate, SettingListResponse,
|
||||
EmailSettings, SMSSettings
|
||||
)
|
||||
|
||||
router = APIRouter(prefix="/settings", tags=["Settings"])
|
||||
|
||||
|
||||
@router.get("/email", response_model=Dict[str, str])
|
||||
async def get_email_settings(
|
||||
token: str = Depends(get_current_user_id),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""Get email settings."""
|
||||
service = SettingsService(db)
|
||||
return service.get_email_settings()
|
||||
|
||||
|
||||
@router.put("/email")
|
||||
async def update_email_settings(
|
||||
settings: EmailSettings,
|
||||
token: str = Depends(get_current_user_id),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""Update email settings."""
|
||||
logger.info(f"Updating email settings: smtp_server={settings.smtp_server}")
|
||||
service = SettingsService(db)
|
||||
service.update_email_settings(settings.dict())
|
||||
|
||||
# Reschedule email fetch if interval changed
|
||||
try:
|
||||
from request_app.main import reschedule_email_fetch
|
||||
reschedule_email_fetch()
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to reschedule email fetch: {e}")
|
||||
|
||||
return {"message": "Email settings updated successfully"}
|
||||
|
||||
|
||||
@router.post("/email/test")
|
||||
async def test_email_settings(
|
||||
data: Dict[str, str],
|
||||
token: str = Depends(get_current_user_id),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""Send test email."""
|
||||
from request_app.integrations.email import EmailClient
|
||||
|
||||
to_email = data.get('to_email')
|
||||
if not to_email:
|
||||
raise HTTPException(status_code=400, detail="to_email is required")
|
||||
|
||||
logger.info(f"Testing email: sending to {to_email}")
|
||||
|
||||
try:
|
||||
email_client = EmailClient(db_session=db)
|
||||
|
||||
result = email_client.send_email(
|
||||
to=to_email,
|
||||
subject="Тестовое письмо - Service Desk",
|
||||
body="Это тестовое письмо для проверки настроек почты.\n\nЕсли вы получили это письмо, настройки работают корректно."
|
||||
)
|
||||
|
||||
if result.get('status') == 'success':
|
||||
logger.info(f"Test email sent successfully to {to_email}")
|
||||
return {"message": f"Тестовое письмо отправлено на {to_email}"}
|
||||
else:
|
||||
logger.error(f"Test email failed: {result.get('error')}")
|
||||
raise HTTPException(status_code=500, detail=result.get('error', 'Unknown error'))
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"Test email error: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=f"Ошибка отправки: {str(e)}")
|
||||
|
||||
|
||||
@router.get("/email/test-connection")
|
||||
async def test_email_connection(
|
||||
token: str = Depends(get_current_user_id),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""Test SMTP connection."""
|
||||
from request_app.integrations.email import EmailClient
|
||||
|
||||
logger.info("Testing SMTP connection")
|
||||
|
||||
try:
|
||||
email_client = EmailClient(db_session=db)
|
||||
result = email_client.test_connection()
|
||||
|
||||
if result.get('status') == 'success':
|
||||
return {"message": "Подключение к SMTP серверу успешно"}
|
||||
else:
|
||||
raise HTTPException(status_code=500, detail=result.get('error', 'Connection failed'))
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"SMTP connection test error: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=f"Ошибка подключения: {str(e)}")
|
||||
|
||||
|
||||
@router.get("/email/test-imap")
|
||||
async def test_imap_connection(
|
||||
token: str = Depends(get_current_user_id),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""Test IMAP connection."""
|
||||
import imaplib
|
||||
import ssl as ssl_mod
|
||||
from request_app.integrations.email import EmailClient
|
||||
|
||||
logger.info("Testing IMAP connection")
|
||||
|
||||
try:
|
||||
email_client = EmailClient(db_session=db)
|
||||
context = ssl_mod.create_default_context()
|
||||
mail = imaplib.IMAP4_SSL(email_client.imap_server, email_client.imap_port, ssl_context=context)
|
||||
mail.login(email_client.username, email_client.password)
|
||||
mail.select("INBOX", readonly=True)
|
||||
status, data = mail.search(None, "ALL")
|
||||
count = len(data[0].split()) if data[0] else 0
|
||||
mail.logout()
|
||||
return {"message": f"Подключение к IMAP успешно. Писем в INBOX: {count}"}
|
||||
except Exception as e:
|
||||
logger.error(f"IMAP connection test error: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=f"Ошибка подключения к IMAP: {str(e)}")
|
||||
|
||||
|
||||
@router.post("/email/fetch")
|
||||
async def fetch_emails_now(
|
||||
token: str = Depends(get_current_user_id),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""Manually trigger email fetch from IMAP."""
|
||||
logger.info("Manual email fetch triggered")
|
||||
|
||||
try:
|
||||
from request_app.workers.email_worker import fetch_incoming_emails
|
||||
result = fetch_incoming_emails(force=True)
|
||||
# Normalize response - always return expected keys
|
||||
return {
|
||||
"status": result.get("status", "unknown"),
|
||||
"fetched": result.get("fetched", 0),
|
||||
"created": result.get("created", 0),
|
||||
"attached": result.get("attached", 0),
|
||||
}
|
||||
except Exception as e:
|
||||
logger.error(f"Email fetch error: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=f"Ошибка сбора почты: {str(e)}")
|
||||
|
||||
|
||||
@router.get("/email/outbox")
|
||||
async def get_outbox_stats(
|
||||
token: str = Depends(get_current_user_id),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""Get email outbox queue statistics."""
|
||||
from request_app.services.email_outbox_service import EmailOutboxService
|
||||
svc = EmailOutboxService(db)
|
||||
return svc.get_stats()
|
||||
|
||||
|
||||
@router.post("/email/outbox/process")
|
||||
async def process_outbox_now(
|
||||
token: str = Depends(get_current_user_id),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""Manually trigger outbox processing."""
|
||||
from request_app.services.email_outbox_service import EmailOutboxService
|
||||
svc = EmailOutboxService(db)
|
||||
return svc.process_queue()
|
||||
|
||||
|
||||
@router.post("/email/outbox/reset")
|
||||
async def reset_outbox_failed(
|
||||
token: str = Depends(get_current_user_id),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""Reset failed emails back to pending for retry."""
|
||||
from request_app.services.email_outbox_service import EmailOutboxService
|
||||
svc = EmailOutboxService(db)
|
||||
count = svc.reset_failed()
|
||||
return {"reset": count}
|
||||
|
||||
|
||||
@router.get("/sms", response_model=Dict[str, str])
|
||||
async def get_sms_settings(
|
||||
token: str = Depends(get_current_user_id),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""Get SMS settings."""
|
||||
service = SettingsService(db)
|
||||
return service.get_sms_settings()
|
||||
|
||||
|
||||
@router.put("/sms")
|
||||
async def update_sms_settings(
|
||||
settings: SMSSettings,
|
||||
token: str = Depends(get_current_user_id),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""Update SMS settings."""
|
||||
logger.info("Updating SMS settings")
|
||||
service = SettingsService(db)
|
||||
service.update_sms_settings(settings.dict())
|
||||
return {"message": "SMS settings updated successfully"}
|
||||
|
||||
|
||||
@router.post("/sms/test")
|
||||
async def test_sms_settings(
|
||||
data: Dict[str, str],
|
||||
token: str = Depends(get_current_user_id),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""Send test SMS."""
|
||||
from request_app.integrations.sms import SMSClient
|
||||
|
||||
to_phone = data.get('to_phone')
|
||||
if not to_phone:
|
||||
raise HTTPException(status_code=400, detail="to_phone is required")
|
||||
|
||||
logger.info(f"Testing SMS: sending to {to_phone}")
|
||||
|
||||
try:
|
||||
service = SettingsService(db)
|
||||
sms_settings = service.get_sms_settings()
|
||||
|
||||
sms_type = sms_settings.get('sms_type', 'twilio')
|
||||
|
||||
if sms_type == 'custom':
|
||||
# Custom SMS gateway
|
||||
import requests as req
|
||||
gateway_url = sms_settings.get('gateway_url', '')
|
||||
if not gateway_url:
|
||||
raise HTTPException(status_code=400, detail="Gateway URL not configured")
|
||||
|
||||
logger.info(f"Using custom SMS gateway: {gateway_url}")
|
||||
|
||||
response = req.post(gateway_url, json={
|
||||
'to': to_phone,
|
||||
'message': 'Тестовое SMS - Service Desk. Настройки работают корректно.',
|
||||
'from': sms_settings.get('gateway_from', '')
|
||||
})
|
||||
|
||||
if response.status_code == 200:
|
||||
logger.info(f"Test SMS sent via custom gateway to {to_phone}")
|
||||
return {"message": f"Тестовое SMS отправлено на {to_phone}"}
|
||||
else:
|
||||
logger.error(f"Custom gateway error: {response.text}")
|
||||
raise HTTPException(status_code=500, detail=f"Gateway error: {response.text}")
|
||||
else:
|
||||
# Twilio
|
||||
sms_client = SMSClient(db_session=db)
|
||||
|
||||
result = sms_client.send_sms(
|
||||
to=to_phone,
|
||||
message="Тестовое SMS - Service Desk. Настройки работают корректно."
|
||||
)
|
||||
|
||||
if result.get('status') == 'success':
|
||||
logger.info(f"Test SMS sent via Twilio to {to_phone}")
|
||||
return {"message": f"Тестовое SMS отправлено на {to_phone}"}
|
||||
else:
|
||||
logger.error(f"Twilio SMS failed: {result.get('error')}")
|
||||
raise HTTPException(status_code=500, detail=result.get('error', 'Unknown error'))
|
||||
except HTTPException:
|
||||
raise
|
||||
except Exception as e:
|
||||
logger.error(f"Test SMS error: {e}", exc_info=True)
|
||||
raise HTTPException(status_code=500, detail=f"Ошибка отправки: {str(e)}")
|
||||
|
||||
|
||||
@router.get("/logging")
|
||||
async def get_logging_settings(
|
||||
token: str = Depends(get_current_user_id),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""Get current logging configuration."""
|
||||
from request_app.core.logging import get_log_config, LOG_LEVELS
|
||||
config = get_log_config()
|
||||
return {
|
||||
"console_level": config.get("console_level", "INFO"),
|
||||
"file_level": config.get("file_level", "DEBUG"),
|
||||
"max_bytes": config.get("max_bytes", 0),
|
||||
"backup_count": config.get("backup_count", 0),
|
||||
"available_levels": list(LOG_LEVELS.keys()),
|
||||
}
|
||||
|
||||
|
||||
@router.put("/logging")
|
||||
async def update_logging_settings(
|
||||
data: Dict,
|
||||
token: str = Depends(get_current_user_id),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""Update logging levels and rotation settings."""
|
||||
from request_app.core.logging import set_log_level, LOG_LEVELS, setup_logging
|
||||
service = SettingsService(db)
|
||||
|
||||
console_level = data.get("console_level")
|
||||
file_level = data.get("file_level")
|
||||
max_bytes = data.get("max_bytes")
|
||||
backup_count = data.get("backup_count")
|
||||
|
||||
for lvl in [console_level, file_level]:
|
||||
if lvl and lvl.upper() not in LOG_LEVELS:
|
||||
raise HTTPException(status_code=400, detail=f"Invalid level '{lvl}'. Use: {list(LOG_LEVELS.keys())}")
|
||||
|
||||
if max_bytes is not None or backup_count is not None:
|
||||
import logging
|
||||
root = logging.getLogger()
|
||||
for h in list(root.handlers):
|
||||
root.removeHandler(h)
|
||||
setup_logging(
|
||||
console_level=console_level or service.get_setting_value("log_console_level", "INFO"),
|
||||
file_level=file_level or service.get_setting_value("log_file_level", "DEBUG"),
|
||||
max_bytes=max_bytes or int(service.get_setting_value("log_max_bytes", str(5*1024*1024))),
|
||||
backup_count=backup_count or int(service.get_setting_value("log_backup_count", "5")),
|
||||
)
|
||||
else:
|
||||
set_log_level(console_level=console_level, file_level=file_level)
|
||||
|
||||
if console_level:
|
||||
service.update_setting("log_console_level", console_level.upper())
|
||||
if file_level:
|
||||
service.update_setting("log_file_level", file_level.upper())
|
||||
if max_bytes is not None:
|
||||
service.update_setting("log_max_bytes", str(max_bytes))
|
||||
if backup_count is not None:
|
||||
service.update_setting("log_backup_count", str(backup_count))
|
||||
|
||||
from request_app.core.logging import get_log_config
|
||||
return {"message": "Logging settings updated", "config": get_log_config()}
|
||||
|
||||
|
||||
@router.get("/{category}", response_model=SettingListResponse)
|
||||
async def get_settings_by_category(
|
||||
category: str,
|
||||
token: str = Depends(get_current_user_id),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""Get all settings for a category."""
|
||||
service = SettingsService(db)
|
||||
settings = service.get_settings_by_category(category)
|
||||
return SettingListResponse(category=category, settings=settings)
|
||||
|
||||
|
||||
@router.put("/{key}")
|
||||
async def update_setting(
|
||||
key: str,
|
||||
setting_data: SettingUpdate,
|
||||
token: str = Depends(get_current_user_id),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""Update a single setting."""
|
||||
service = SettingsService(db)
|
||||
setting = service.update_setting(key, setting_data.value)
|
||||
return {"message": f"Setting '{key}' updated successfully"}
|
||||
@@ -0,0 +1,207 @@
|
||||
"""Ticket routes."""
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, status, Query, Response
|
||||
from sqlalchemy.orm import Session
|
||||
from typing import List, Optional
|
||||
|
||||
from request_app.core.database import get_db
|
||||
from request_app.core.auth import get_current_user_id, get_current_user
|
||||
from request_app.core.exceptions import NotFoundException
|
||||
from request_app.schemas.ticket import (
|
||||
TicketCreate,
|
||||
TicketUpdate,
|
||||
TicketResponse,
|
||||
TicketListResponse,
|
||||
CommentCreate,
|
||||
CommentResponse
|
||||
)
|
||||
from request_app.schemas.common import PaginationParams
|
||||
from request_app.services.ticket_service import TicketService
|
||||
from request_app.services.user_service import UserService
|
||||
|
||||
router = APIRouter(prefix="/tickets", tags=["Tickets"])
|
||||
|
||||
|
||||
@router.get("", response_model=TicketListResponse)
|
||||
async def get_tickets(
|
||||
page: int = Query(1, ge=1),
|
||||
page_size: int = Query(10, ge=1, le=100),
|
||||
status_id: Optional[int] = Query(None),
|
||||
priority_id: Optional[int] = Query(None),
|
||||
assigned_to_id: Optional[int] = Query(None),
|
||||
search: Optional[str] = Query(None),
|
||||
user_id: Optional[int] = Query(None, description="Filter by user"),
|
||||
token: str = Depends(get_current_user_id),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""Get paginated list of tickets."""
|
||||
ticket_service = TicketService(db)
|
||||
|
||||
tickets, total = ticket_service.get_tickets(
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
status_id=status_id,
|
||||
priority_id=priority_id,
|
||||
assigned_to_id=assigned_to_id,
|
||||
search=search,
|
||||
user_id=user_id
|
||||
)
|
||||
|
||||
return TicketListResponse(
|
||||
tickets=[ticket for ticket in tickets],
|
||||
total=total,
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
total_pages=(total + page_size - 1) // page_size
|
||||
)
|
||||
|
||||
|
||||
@router.get("/{ticket_id}", response_model=TicketResponse)
|
||||
async def get_ticket(
|
||||
ticket_id: int,
|
||||
token: str = Depends(get_current_user_id),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""Get ticket by ID."""
|
||||
ticket_service = TicketService(db)
|
||||
ticket = ticket_service.get_ticket_by_id(ticket_id)
|
||||
return ticket
|
||||
|
||||
|
||||
@router.post("", response_model=TicketResponse, status_code=status.HTTP_201_CREATED)
|
||||
async def create_ticket(
|
||||
ticket_data: TicketCreate,
|
||||
user_id: int = Depends(get_current_user_id),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""Create a new ticket."""
|
||||
ticket_service = TicketService(db)
|
||||
ticket = ticket_service.create_ticket(ticket_data, user_id)
|
||||
return ticket
|
||||
|
||||
|
||||
@router.put("/{ticket_id}", response_model=TicketResponse)
|
||||
async def update_ticket(
|
||||
ticket_id: int,
|
||||
ticket_data: TicketUpdate,
|
||||
user_id: int = Depends(get_current_user_id),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""Update ticket."""
|
||||
ticket_service = TicketService(db)
|
||||
ticket = ticket_service.update_ticket(ticket_id, ticket_data, user_id)
|
||||
return ticket
|
||||
|
||||
|
||||
@router.delete("/{ticket_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
async def delete_ticket(
|
||||
ticket_id: int,
|
||||
token: str = Depends(get_current_user_id),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""Delete ticket."""
|
||||
ticket_service = TicketService(db)
|
||||
ticket_service.delete_ticket(ticket_id)
|
||||
return Response(status_code=status.HTTP_204_NO_CONTENT)
|
||||
|
||||
|
||||
@router.get("/{ticket_id}/comments", response_model=List[CommentResponse])
|
||||
async def get_ticket_comments(
|
||||
ticket_id: int,
|
||||
token: str = Depends(get_current_user_id),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""Get all comments for a ticket."""
|
||||
ticket_service = TicketService(db)
|
||||
comments = ticket_service.get_ticket_comments(ticket_id)
|
||||
return comments
|
||||
|
||||
|
||||
@router.post("/{ticket_id}/comments", response_model=CommentResponse, status_code=status.HTTP_201_CREATED)
|
||||
async def add_comment(
|
||||
ticket_id: int,
|
||||
comment_data: CommentCreate,
|
||||
user_id: int = Depends(get_current_user_id),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""Add comment to ticket."""
|
||||
ticket_service = TicketService(db)
|
||||
comment = ticket_service.add_comment(ticket_id, comment_data.comment_text, user_id)
|
||||
return comment
|
||||
|
||||
|
||||
@router.get("/{ticket_id}/events")
|
||||
async def get_ticket_events(
|
||||
ticket_id: int,
|
||||
token: str = Depends(get_current_user_id),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""Get system events for a ticket."""
|
||||
from request_app.services.ticket_event_service import TicketEventService
|
||||
svc = TicketEventService(db)
|
||||
events = svc.get_ticket_events(ticket_id)
|
||||
return [
|
||||
{
|
||||
"id": e.id,
|
||||
"event_type": e.event_type,
|
||||
"message": e.message,
|
||||
"user_id": e.user_id,
|
||||
"created_at": e.created_at.isoformat() if e.created_at else None
|
||||
}
|
||||
for e in events
|
||||
]
|
||||
|
||||
|
||||
@router.post("/{ticket_id}/reply")
|
||||
async def reply_to_ticket(
|
||||
ticket_id: int,
|
||||
data: dict,
|
||||
user_id: int = Depends(get_current_user_id),
|
||||
db: Session = Depends(get_db)
|
||||
):
|
||||
"""Reply to ticket - adds comment and optionally sends email."""
|
||||
from request_app.services.ticket_service import TicketService
|
||||
from request_app.services.email_message_service import EmailMessageService
|
||||
from request_app.core.logging import logger
|
||||
|
||||
ticket_service = TicketService(db)
|
||||
ticket = ticket_service.get_ticket_by_id(ticket_id)
|
||||
|
||||
message = data.get('message', '')
|
||||
send_email = data.get('send_email', False)
|
||||
|
||||
# Add comment
|
||||
comment = ticket_service.add_comment(ticket_id, message, user_id)
|
||||
|
||||
# Send notification
|
||||
ticket_service._notify(ticket, 'ticket_commented', user_id)
|
||||
|
||||
result = {"comment_id": comment.id, "message": "Reply added"}
|
||||
|
||||
# Send email if requested
|
||||
if send_email:
|
||||
try:
|
||||
from request_app.models.user import User
|
||||
requester = db.query(User).filter(User.id == ticket.opened_by).first()
|
||||
|
||||
if requester and requester.email:
|
||||
email_service = EmailMessageService(db)
|
||||
import re
|
||||
clean_subject = re.sub(r"^\[#\d+\]\s*", "", ticket.subject)
|
||||
email_msg = email_service.send_reply(
|
||||
ticket_id=ticket_id,
|
||||
user_id=user_id,
|
||||
to_addresses=requester.email,
|
||||
subject=f"Re: {clean_subject} №{ticket_id}",
|
||||
body_text=message,
|
||||
body_html=message
|
||||
)
|
||||
result['email_sent'] = True
|
||||
result['email_id'] = email_msg.id
|
||||
logger.info(f"Reply email saved for ticket {ticket_id}, email_id={email_msg.id}")
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to send reply email: {e}")
|
||||
result['email_sent'] = False
|
||||
result['email_error'] = str(e)
|
||||
|
||||
return result
|
||||
@@ -0,0 +1,383 @@
|
||||
"""Users routes."""
|
||||
|
||||
from fastapi import APIRouter, Depends, Query, Header, HTTPException
|
||||
from sqlalchemy.orm import Session
|
||||
from typing import Optional
|
||||
|
||||
from request_app.core.database import get_db
|
||||
from request_app.core.auth import get_current_user
|
||||
from request_app.core.security import get_password_hash, verify_password
|
||||
from request_app.models.user import User
|
||||
from request_app.models.role import Role
|
||||
from request_app.models.user_role import UserRole
|
||||
from request_app.models.ticket import Ticket
|
||||
|
||||
router = APIRouter(tags=["Users"])
|
||||
|
||||
|
||||
def _get_user_roles(user: User) -> list:
|
||||
"""Get user role names."""
|
||||
return [ur.role.name for ur in user.user_roles if ur.role]
|
||||
|
||||
|
||||
def _handle_user_deletion(db: Session, user: User):
|
||||
"""Handle ticket reassignment when deleting a user."""
|
||||
# Unassign tickets where user was assigned
|
||||
assigned_tickets = db.query(Ticket).filter(Ticket.assigned_to_id == user.id).all()
|
||||
for ticket in assigned_tickets:
|
||||
ticket.assigned_to_id = None
|
||||
# Mark as unread by clearing a flag or adding an event
|
||||
# For now, we'll just unassign
|
||||
db.flush()
|
||||
|
||||
|
||||
@router.post("/sync")
|
||||
async def sync_user(
|
||||
data: dict,
|
||||
x_api_key: str = Header(None),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""Receive user sync from platform. Protected by API key."""
|
||||
from request_app.settings import get_settings
|
||||
settings = get_settings()
|
||||
if settings.PLATFORM_API_KEY and x_api_key != settings.PLATFORM_API_KEY:
|
||||
raise HTTPException(status_code=401, detail="Unauthorized")
|
||||
|
||||
platform_id = data.get("id")
|
||||
email = data.get("email")
|
||||
if not platform_id or not email:
|
||||
raise HTTPException(status_code=400, detail="id and email required")
|
||||
|
||||
user = db.query(User).filter(User.email == email).first()
|
||||
if not user:
|
||||
user = User(
|
||||
email=email,
|
||||
first_name=data.get("first_name", ""),
|
||||
last_name=data.get("last_name", ""),
|
||||
is_active=data.get("is_active", True),
|
||||
source="platform",
|
||||
)
|
||||
db.add(user)
|
||||
db.flush()
|
||||
else:
|
||||
user.first_name = data.get("first_name", user.first_name)
|
||||
user.last_name = data.get("last_name", user.last_name)
|
||||
user.is_active = data.get("is_active", user.is_active)
|
||||
user.source = "platform"
|
||||
|
||||
# Sync roles from platform
|
||||
platform_roles = data.get("roles", [])
|
||||
if platform_roles is not None:
|
||||
# Clear existing roles
|
||||
db.query(UserRole).filter(UserRole.user_id == user.id).delete()
|
||||
|
||||
# Assign new roles
|
||||
for role_name in platform_roles:
|
||||
role = db.query(Role).filter(Role.name == role_name).first()
|
||||
if role:
|
||||
db.add(UserRole(user_id=user.id, role_id=role.id))
|
||||
|
||||
db.commit()
|
||||
return {"status": "ok", "user_id": user.id, "roles": _get_user_roles(user)}
|
||||
|
||||
|
||||
@router.post("/sync-all")
|
||||
async def sync_all_users(
|
||||
data: dict,
|
||||
x_api_key: str = Header(None),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""Sync all platform users. Deletes platform users not in the list."""
|
||||
from request_app.settings import get_settings
|
||||
settings = get_settings()
|
||||
if settings.PLATFORM_API_KEY and x_api_key != settings.PLATFORM_API_KEY:
|
||||
raise HTTPException(status_code=401, detail="Unauthorized")
|
||||
|
||||
platform_users = data.get("users", [])
|
||||
platform_emails = {u["email"] for u in platform_users}
|
||||
|
||||
# Get all platform users in local DB
|
||||
local_platform_users = db.query(User).filter(User.source == "platform").all()
|
||||
|
||||
# Delete platform users not in the list
|
||||
deleted_count = 0
|
||||
for user in local_platform_users:
|
||||
if user.email not in platform_emails:
|
||||
_handle_user_deletion(db, user)
|
||||
db.delete(user)
|
||||
deleted_count += 1
|
||||
|
||||
# Sync/create users from platform
|
||||
for user_data in platform_users:
|
||||
email = user_data.get("email")
|
||||
if not email:
|
||||
continue
|
||||
user = db.query(User).filter(User.email == email).first()
|
||||
if not user:
|
||||
user = User(
|
||||
email=email,
|
||||
first_name=user_data.get("first_name", ""),
|
||||
last_name=user_data.get("last_name", ""),
|
||||
is_active=user_data.get("is_active", True),
|
||||
source="platform",
|
||||
)
|
||||
db.add(user)
|
||||
else:
|
||||
user.first_name = user_data.get("first_name", user.first_name)
|
||||
user.last_name = user_data.get("last_name", user.last_name)
|
||||
user.is_active = user_data.get("is_active", user.is_active)
|
||||
user.source = "platform"
|
||||
|
||||
db.commit()
|
||||
return {"status": "ok", "deleted": deleted_count, "synced": len(platform_users)}
|
||||
|
||||
|
||||
@router.delete("/{user_id}")
|
||||
async def delete_user(
|
||||
user_id: int,
|
||||
x_api_key: str = Header(None),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
"""Delete user. Can be called by platform or locally."""
|
||||
from request_app.settings import get_settings
|
||||
settings = get_settings()
|
||||
|
||||
# Check if called from platform
|
||||
is_platform_call = x_api_key and x_api_key == settings.PLATFORM_API_KEY
|
||||
|
||||
user = db.query(User).filter(User.id == user_id).first()
|
||||
if not user:
|
||||
return {"status": "ok", "message": "User not found"}
|
||||
|
||||
if not is_platform_call and user.source == "platform":
|
||||
raise HTTPException(status_code=403, detail="Cannot delete platform users")
|
||||
|
||||
_handle_user_deletion(db, user)
|
||||
db.delete(user)
|
||||
db.commit()
|
||||
return {"status": "ok", "message": "User deleted"}
|
||||
|
||||
|
||||
@router.get("/me")
|
||||
async def get_me(current_user: User = Depends(get_current_user)):
|
||||
"""Get current user."""
|
||||
return {
|
||||
"id": current_user.id,
|
||||
"email": current_user.email,
|
||||
"first_name": current_user.first_name,
|
||||
"last_name": current_user.last_name,
|
||||
"is_active": current_user.is_active,
|
||||
"source": current_user.source,
|
||||
"roles": _get_user_roles(current_user),
|
||||
}
|
||||
|
||||
|
||||
@router.get("")
|
||||
async def get_users(
|
||||
page: int = Query(1, ge=1),
|
||||
page_size: int = Query(10, ge=1, le=100),
|
||||
search: Optional[str] = Query(None),
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user),
|
||||
):
|
||||
"""Get paginated list of users from local DB."""
|
||||
query = db.query(User)
|
||||
if search:
|
||||
term = f"%{search}%"
|
||||
query = query.filter(User.email.ilike(term) | User.first_name.ilike(term) | User.last_name.ilike(term))
|
||||
total = query.count()
|
||||
users = query.offset((page - 1) * page_size).limit(page_size).all()
|
||||
return {
|
||||
"users": [
|
||||
{
|
||||
"id": u.id,
|
||||
"email": u.email,
|
||||
"first_name": u.first_name,
|
||||
"last_name": u.last_name,
|
||||
"is_active": u.is_active,
|
||||
"source": u.source,
|
||||
"roles": _get_user_roles(u),
|
||||
}
|
||||
for u in users
|
||||
],
|
||||
"total": total,
|
||||
"page": page,
|
||||
"page_size": page_size,
|
||||
"total_pages": (total + page_size - 1) // page_size,
|
||||
}
|
||||
|
||||
|
||||
@router.get("/specialists")
|
||||
async def get_specialists(
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user),
|
||||
):
|
||||
"""Get list of specialists (users with support roles)."""
|
||||
# Get users with support_agent, admin, or manager roles
|
||||
specialists = []
|
||||
users = db.query(User).filter(User.is_active == True).all()
|
||||
for user in users:
|
||||
roles = _get_user_roles(user)
|
||||
if any(r in roles for r in ["admin", "support_agent", "manager"]):
|
||||
specialists.append({
|
||||
"id": user.id,
|
||||
"email": user.email,
|
||||
"first_name": user.first_name,
|
||||
"last_name": user.last_name,
|
||||
"is_active": user.is_active,
|
||||
"roles": roles,
|
||||
})
|
||||
return specialists
|
||||
|
||||
|
||||
@router.get("/roles")
|
||||
async def get_roles(db: Session = Depends(get_db)):
|
||||
"""Get all available roles."""
|
||||
roles = db.query(Role).order_by(Role.name).all()
|
||||
return [{"id": r.id, "name": r.name, "description": r.description, "is_system": r.is_system} for r in roles]
|
||||
|
||||
|
||||
@router.get("/{user_id}")
|
||||
async def get_user(
|
||||
user_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user),
|
||||
):
|
||||
"""Get user by ID."""
|
||||
user = db.query(User).filter(User.id == user_id).first()
|
||||
if not user:
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
return {
|
||||
"id": user.id,
|
||||
"email": user.email,
|
||||
"first_name": user.first_name,
|
||||
"last_name": user.last_name,
|
||||
"is_active": user.is_active,
|
||||
"source": user.source,
|
||||
"roles": _get_user_roles(user),
|
||||
}
|
||||
|
||||
|
||||
@router.post("", status_code=201)
|
||||
async def create_user(
|
||||
data: dict,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user),
|
||||
):
|
||||
"""Create a local user."""
|
||||
email = data.get("email")
|
||||
password = data.get("password")
|
||||
first_name = data.get("first_name", "")
|
||||
last_name = data.get("last_name", "")
|
||||
role_ids = data.get("role_ids", [])
|
||||
|
||||
if not email or not password:
|
||||
raise HTTPException(status_code=400, detail="Email and password required")
|
||||
|
||||
if db.query(User).filter(User.email == email).first():
|
||||
raise HTTPException(status_code=409, detail="Email already exists")
|
||||
|
||||
user = User(
|
||||
email=email,
|
||||
first_name=first_name,
|
||||
last_name=last_name,
|
||||
password_hash=get_password_hash(password),
|
||||
is_active=True,
|
||||
source="local",
|
||||
)
|
||||
db.add(user)
|
||||
db.commit()
|
||||
db.refresh(user)
|
||||
|
||||
# Assign roles
|
||||
for role_id in role_ids:
|
||||
role = db.query(Role).filter(Role.id == role_id).first()
|
||||
if role:
|
||||
db.add(UserRole(user_id=user.id, role_id=role.id))
|
||||
db.commit()
|
||||
db.refresh(user)
|
||||
|
||||
return {
|
||||
"id": user.id,
|
||||
"email": user.email,
|
||||
"first_name": user.first_name,
|
||||
"last_name": user.last_name,
|
||||
"is_active": user.is_active,
|
||||
"source": user.source,
|
||||
"roles": _get_user_roles(user),
|
||||
}
|
||||
|
||||
|
||||
@router.put("/{user_id}")
|
||||
async def update_user(
|
||||
user_id: int,
|
||||
data: dict,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user),
|
||||
):
|
||||
"""Update a local user. Platform users cannot be edited."""
|
||||
user = db.query(User).filter(User.id == user_id).first()
|
||||
if not user:
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
|
||||
if user.source == "platform":
|
||||
raise HTTPException(status_code=403, detail="Cannot edit platform users")
|
||||
|
||||
if "first_name" in data:
|
||||
user.first_name = data["first_name"]
|
||||
if "last_name" in data:
|
||||
user.last_name = data["last_name"]
|
||||
if "email" in data:
|
||||
existing = db.query(User).filter(User.email == data["email"], User.id != user_id).first()
|
||||
if existing:
|
||||
raise HTTPException(status_code=409, detail="Email already exists")
|
||||
user.email = data["email"]
|
||||
if "phone" in data:
|
||||
user.phone = data["phone"]
|
||||
if "is_active" in data:
|
||||
user.is_active = data["is_active"]
|
||||
if "password" in data and data["password"]:
|
||||
user.password_hash = get_password_hash(data["password"])
|
||||
|
||||
# Update roles if provided
|
||||
if "role_ids" in data:
|
||||
# Remove existing roles
|
||||
db.query(UserRole).filter(UserRole.user_id == user.id).delete()
|
||||
# Add new roles
|
||||
for role_id in data["role_ids"]:
|
||||
role = db.query(Role).filter(Role.id == role_id).first()
|
||||
if role:
|
||||
db.add(UserRole(user_id=user.id, role_id=role.id))
|
||||
|
||||
db.commit()
|
||||
db.refresh(user)
|
||||
|
||||
return {
|
||||
"id": user.id,
|
||||
"email": user.email,
|
||||
"first_name": user.first_name,
|
||||
"last_name": user.last_name,
|
||||
"is_active": user.is_active,
|
||||
"source": user.source,
|
||||
"roles": _get_user_roles(user),
|
||||
}
|
||||
|
||||
|
||||
@router.delete("/{user_id}/local")
|
||||
async def deactivate_local_user(
|
||||
user_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user),
|
||||
):
|
||||
"""Deactivate a local user. Platform users cannot be deactivated."""
|
||||
user = db.query(User).filter(User.id == user_id).first()
|
||||
if not user:
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
|
||||
if user.source == "platform":
|
||||
raise HTTPException(status_code=403, detail="Cannot deactivate platform users")
|
||||
|
||||
user.is_active = False
|
||||
db.commit()
|
||||
|
||||
return {"message": "User deactivated"}
|
||||
@@ -0,0 +1,5 @@
|
||||
"""Configuration settings - delegates to app.settings."""
|
||||
|
||||
from request_app.settings import Settings, get_settings
|
||||
|
||||
__all__ = ["Settings", "get_settings"]
|
||||
@@ -0,0 +1,24 @@
|
||||
"""Core module."""
|
||||
|
||||
from .security import decode_platform_token, get_user_id_from_token, get_roles_from_token
|
||||
from .database import get_db, engine, init_db
|
||||
from .exceptions import AppException, NotFoundException, UnauthorizedException
|
||||
from .middleware import add_security_headers, add_cors_middleware
|
||||
from .platform_client import PlatformUser, PlatformClient, get_platform_client
|
||||
|
||||
__all__ = [
|
||||
"decode_platform_token",
|
||||
"get_user_id_from_token",
|
||||
"get_roles_from_token",
|
||||
"get_db",
|
||||
"engine",
|
||||
"init_db",
|
||||
"AppException",
|
||||
"NotFoundException",
|
||||
"UnauthorizedException",
|
||||
"add_security_headers",
|
||||
"add_cors_middleware",
|
||||
"PlatformUser",
|
||||
"PlatformClient",
|
||||
"get_platform_client",
|
||||
]
|
||||
@@ -0,0 +1,116 @@
|
||||
"""Authentication dependencies for platform integration."""
|
||||
|
||||
from fastapi import Depends, HTTPException, status
|
||||
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from request_app.core.database import get_db
|
||||
from request_app.core.security import decode_platform_token, get_user_id_from_token
|
||||
from request_app.core.platform_client import PlatformUser, get_platform_client
|
||||
from request_app.models.user import User
|
||||
|
||||
security = HTTPBearer()
|
||||
|
||||
|
||||
def get_current_user_id(
|
||||
credentials: HTTPAuthorizationCredentials = Depends(security),
|
||||
) -> int:
|
||||
"""Extract user ID from platform JWT token."""
|
||||
token = credentials.credentials
|
||||
try:
|
||||
return get_user_id_from_token(token)
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token")
|
||||
|
||||
|
||||
def _sync_platform_user_to_local(db: Session, payload: dict) -> User:
|
||||
"""Create or update local user from platform JWT claims."""
|
||||
email = payload.get("email", "")
|
||||
first_name = payload.get("first_name", "")
|
||||
last_name = payload.get("last_name", "")
|
||||
|
||||
user = db.query(User).filter(User.email == email).first()
|
||||
if not user:
|
||||
user = User(
|
||||
email=email,
|
||||
first_name=first_name,
|
||||
last_name=last_name,
|
||||
is_active=True,
|
||||
source="platform",
|
||||
)
|
||||
db.add(user)
|
||||
db.commit()
|
||||
db.refresh(user)
|
||||
else:
|
||||
user.first_name = first_name or user.first_name
|
||||
user.last_name = last_name or user.last_name
|
||||
user.is_active = payload.get("is_active", True)
|
||||
user.source = "platform"
|
||||
db.commit()
|
||||
|
||||
return user
|
||||
|
||||
|
||||
def get_current_user(
|
||||
credentials: HTTPAuthorizationCredentials = Depends(security),
|
||||
db: Session = Depends(get_db),
|
||||
) -> User:
|
||||
"""Get current authenticated user, auto-syncing from platform."""
|
||||
token = credentials.credentials
|
||||
try:
|
||||
user_id = get_user_id_from_token(token)
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token")
|
||||
|
||||
payload = decode_platform_token(token)
|
||||
if not payload:
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token")
|
||||
|
||||
user = _sync_platform_user_to_local(db, payload)
|
||||
|
||||
if not user.is_active:
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="User is deactivated")
|
||||
|
||||
return user
|
||||
|
||||
|
||||
def get_current_platform_user(
|
||||
credentials: HTTPAuthorizationCredentials = Depends(security),
|
||||
) -> PlatformUser:
|
||||
"""Get PlatformUser from JWT (for role checks)."""
|
||||
token = credentials.credentials
|
||||
try:
|
||||
user_id = get_user_id_from_token(token)
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token")
|
||||
|
||||
payload = decode_platform_token(token)
|
||||
if not payload:
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token")
|
||||
|
||||
return PlatformUser(
|
||||
id=user_id,
|
||||
email=payload.get("email", ""),
|
||||
first_name=payload.get("first_name", ""),
|
||||
last_name=payload.get("last_name", ""),
|
||||
is_active=payload.get("is_active", True),
|
||||
roles=payload.get("roles", []),
|
||||
)
|
||||
|
||||
|
||||
def require_admin(
|
||||
user: PlatformUser = Depends(get_current_platform_user),
|
||||
) -> PlatformUser:
|
||||
"""Require admin role."""
|
||||
if not user.has_role("admin"):
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Admin access required")
|
||||
return user
|
||||
|
||||
|
||||
def require_role(role_name: str):
|
||||
"""Dependency factory: require a specific role."""
|
||||
def _check_role(user: PlatformUser = Depends(get_current_platform_user)) -> PlatformUser:
|
||||
if not user.has_role(role_name):
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail=f"Role '{role_name}' required")
|
||||
return user
|
||||
return _check_role
|
||||
@@ -0,0 +1,64 @@
|
||||
"""Database utilities and session management."""
|
||||
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker, Session
|
||||
from typing import Generator
|
||||
from request_app.settings import get_settings
|
||||
from request_app.models.base import Base
|
||||
|
||||
# Create database engine
|
||||
settings = get_settings()
|
||||
engine = create_engine(
|
||||
settings.DATABASE_URL,
|
||||
pool_pre_ping=True,
|
||||
echo=settings.APP_DEBUG
|
||||
)
|
||||
|
||||
# Create session factory
|
||||
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
||||
|
||||
|
||||
def get_db() -> Generator[Session, None, None]:
|
||||
"""
|
||||
Dependency function to get database session.
|
||||
Yields a session and ensures it's closed after use.
|
||||
"""
|
||||
db = SessionLocal()
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def init_db():
|
||||
"""Initialize database - create all tables and default data."""
|
||||
from request_app.models import (
|
||||
user, priority, status, category,
|
||||
ticket, comment, notification, extra
|
||||
)
|
||||
from request_app.models.role import Role
|
||||
from request_app.models.user_role import UserRole
|
||||
|
||||
Base.metadata.create_all(bind=engine)
|
||||
|
||||
# Create default roles
|
||||
db = SessionLocal()
|
||||
try:
|
||||
default_roles = [
|
||||
("admin", "Administrator with full access", True),
|
||||
("support_agent", "Support agent - create and update tickets", True),
|
||||
("manager", "Manager - view all tickets, create teams", True),
|
||||
("customer", "Customer - read-only, create tickets", True),
|
||||
]
|
||||
for name, description, is_system in default_roles:
|
||||
if not db.query(Role).filter(Role.name == name).first():
|
||||
db.add(Role(name=name, description=description, is_system=is_system))
|
||||
db.commit()
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
"""Initialize database when running as script."""
|
||||
init_db()
|
||||
print("Database initialized successfully!")
|
||||
@@ -0,0 +1,51 @@
|
||||
"""Custom exception handlers."""
|
||||
|
||||
from fastapi import Request, status
|
||||
from fastapi.responses import JSONResponse
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from pydantic import ValidationError
|
||||
from request_app.core.exceptions import AppException
|
||||
|
||||
|
||||
async def app_exception_handler(request: Request, exc: Exception):
|
||||
"""Handle all unhandled exceptions."""
|
||||
if isinstance(exc, AppException):
|
||||
return JSONResponse(
|
||||
status_code=exc.status_code,
|
||||
content={
|
||||
"message": exc.message,
|
||||
"error_code": exc.error_code,
|
||||
"success": False
|
||||
}
|
||||
)
|
||||
return JSONResponse(
|
||||
status_code=status.HTTP_500_INTERNAL_SERVER_ERROR,
|
||||
content={
|
||||
"message": "Internal server error",
|
||||
"success": False
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
async def validation_exception_handler(request: Request, exc: RequestValidationError):
|
||||
"""Handle validation errors."""
|
||||
return JSONResponse(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
content={
|
||||
"message": "Validation error",
|
||||
"errors": exc.errors(),
|
||||
"success": False
|
||||
}
|
||||
)
|
||||
|
||||
|
||||
async def pydantic_validation_exception_handler(request: Request, exc: ValidationError):
|
||||
"""Handle Pydantic validation errors."""
|
||||
return JSONResponse(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
content={
|
||||
"message": "Validation error",
|
||||
"errors": exc.errors(),
|
||||
"success": False
|
||||
}
|
||||
)
|
||||
@@ -0,0 +1,54 @@
|
||||
"""Custom exception classes."""
|
||||
|
||||
from typing import Optional
|
||||
|
||||
|
||||
class AppException(Exception):
|
||||
"""Base application exception."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
message: str,
|
||||
status_code: int = 500,
|
||||
error_code: Optional[str] = None
|
||||
):
|
||||
self.message = message
|
||||
self.status_code = status_code
|
||||
self.error_code = error_code
|
||||
super().__init__(self.message)
|
||||
|
||||
|
||||
class NotFoundException(AppException):
|
||||
"""Resource not found exception."""
|
||||
|
||||
def __init__(self, message: str = "Resource not found"):
|
||||
super().__init__(message, status_code=404, error_code="NOT_FOUND")
|
||||
|
||||
|
||||
class UnauthorizedException(AppException):
|
||||
"""Authentication/authorization exception."""
|
||||
|
||||
def __init__(self, message: str = "Unauthorized access"):
|
||||
super().__init__(message, status_code=401, error_code="UNAUTHORIZED")
|
||||
|
||||
|
||||
class ForbiddenException(AppException):
|
||||
"""Permission denied exception."""
|
||||
|
||||
def __init__(self, message: str = "Permission denied"):
|
||||
super().__init__(message, status_code=403, error_code="FORBIDDEN")
|
||||
|
||||
|
||||
class ValidationException(AppException):
|
||||
"""Validation error exception."""
|
||||
|
||||
def __init__(self, message: str, details: Optional[list] = None):
|
||||
super().__init__(message, status_code=422, error_code="VALIDATION_ERROR")
|
||||
self.details = details or []
|
||||
|
||||
|
||||
class ConflictException(AppException):
|
||||
"""Resource conflict exception."""
|
||||
|
||||
def __init__(self, message: str = "Resource already exists"):
|
||||
super().__init__(message, status_code=409, error_code="CONFLICT")
|
||||
@@ -0,0 +1,112 @@
|
||||
"""Logging configuration with rotation and configurable levels."""
|
||||
|
||||
import logging
|
||||
import sys
|
||||
from pathlib import Path
|
||||
from logging.handlers import RotatingFileHandler
|
||||
|
||||
# Create logs directory
|
||||
LOGS_DIR = Path(__file__).parent.parent.parent / "logs"
|
||||
LOGS_DIR.mkdir(exist_ok=True)
|
||||
|
||||
# Store handlers for dynamic level changes
|
||||
_console_handler = None
|
||||
_file_handler = None
|
||||
_error_handler = None
|
||||
|
||||
# Rotation defaults
|
||||
DEFAULT_MAX_BYTES = 5 * 1024 * 1024 # 5 MB per file
|
||||
DEFAULT_BACKUP_COUNT = 5 # Keep 5 rotated files
|
||||
|
||||
LOG_LEVELS = {
|
||||
"DEBUG": logging.DEBUG,
|
||||
"INFO": logging.INFO,
|
||||
"WARNING": logging.WARNING,
|
||||
"ERROR": logging.ERROR,
|
||||
}
|
||||
|
||||
|
||||
def setup_logging(console_level: str = "INFO", file_level: str = "DEBUG",
|
||||
max_bytes: int = DEFAULT_MAX_BYTES, backup_count: int = DEFAULT_BACKUP_COUNT):
|
||||
"""Setup application logging with rotation."""
|
||||
global _console_handler, _file_handler, _error_handler
|
||||
|
||||
root_logger = logging.getLogger()
|
||||
root_logger.setLevel(logging.DEBUG)
|
||||
|
||||
file_format = logging.Formatter(
|
||||
'%(asctime)s %(levelname)-8s %(name)s [%(filename)s:%(lineno)d]: %(message)s',
|
||||
datefmt='%Y-%m-%d %H:%M:%S'
|
||||
)
|
||||
console_format = logging.Formatter(
|
||||
'%(asctime)s %(levelname)-8s %(name)s: %(message)s',
|
||||
datefmt='%Y-%m-%d %H:%M:%S'
|
||||
)
|
||||
|
||||
# Console handler
|
||||
_console_handler = logging.StreamHandler(sys.stdout)
|
||||
_console_handler.setLevel(LOG_LEVELS.get(console_level.upper(), logging.INFO))
|
||||
_console_handler.setFormatter(console_format)
|
||||
|
||||
# Rotating file handler for all logs
|
||||
_file_handler = RotatingFileHandler(
|
||||
LOGS_DIR / "app.log",
|
||||
maxBytes=max_bytes,
|
||||
backupCount=backup_count,
|
||||
encoding='utf-8'
|
||||
)
|
||||
_file_handler.setLevel(LOG_LEVELS.get(file_level.upper(), logging.DEBUG))
|
||||
_file_handler.setFormatter(file_format)
|
||||
|
||||
# Rotating file handler for errors only
|
||||
_error_handler = RotatingFileHandler(
|
||||
LOGS_DIR / "error.log",
|
||||
maxBytes=max_bytes,
|
||||
backupCount=backup_count,
|
||||
encoding='utf-8'
|
||||
)
|
||||
_error_handler.setLevel(logging.ERROR)
|
||||
_error_handler.setFormatter(file_format)
|
||||
|
||||
root_logger.addHandler(_console_handler)
|
||||
root_logger.addHandler(_file_handler)
|
||||
root_logger.addHandler(_error_handler)
|
||||
|
||||
# Reduce noise from libraries
|
||||
logging.getLogger("urllib3").setLevel(logging.WARNING)
|
||||
logging.getLogger("sqlalchemy.engine").setLevel(logging.WARNING)
|
||||
|
||||
return root_logger
|
||||
|
||||
|
||||
def set_log_level(console_level: str = None, file_level: str = None):
|
||||
"""Change log levels at runtime."""
|
||||
changed = []
|
||||
if console_level and console_level.upper() in LOG_LEVELS:
|
||||
_console_handler.setLevel(LOG_LEVELS[console_level.upper()])
|
||||
changed.append(f"console={console_level.upper()}")
|
||||
if file_level and file_level.upper() in LOG_LEVELS:
|
||||
_file_handler.setLevel(LOG_LEVELS[file_level.upper()])
|
||||
changed.append(f"file={file_level.upper()}")
|
||||
if changed:
|
||||
logger.info(f"Log levels changed: {', '.join(changed)}")
|
||||
return bool(changed)
|
||||
|
||||
|
||||
def get_log_config() -> dict:
|
||||
"""Return current logging configuration."""
|
||||
return {
|
||||
"console_level": logging.getLevelName(_console_handler.level) if _console_handler else "N/A",
|
||||
"file_level": logging.getLevelName(_file_handler.level) if _file_handler else "N/A",
|
||||
"max_bytes": _file_handler.maxBytes if _file_handler else 0,
|
||||
"backup_count": _file_handler.backupCount if _file_handler else 0,
|
||||
}
|
||||
|
||||
|
||||
# Logger instances
|
||||
logger = logging.getLogger("app")
|
||||
email_logger = logging.getLogger("app.email")
|
||||
sms_logger = logging.getLogger("app.sms")
|
||||
auth_logger = logging.getLogger("app.auth")
|
||||
ticket_logger = logging.getLogger("app.ticket")
|
||||
notification_logger = logging.getLogger("app.notification")
|
||||
@@ -0,0 +1,46 @@
|
||||
"""Middleware for authentication and security headers."""
|
||||
|
||||
from fastapi import Request, Response
|
||||
from starlette.middleware.base import BaseHTTPMiddleware
|
||||
from starlette.middleware.cors import CORSMiddleware
|
||||
from fastapi import FastAPI
|
||||
import os
|
||||
|
||||
|
||||
def add_security_headers(app: FastAPI):
|
||||
"""Add security headers to all responses."""
|
||||
|
||||
class SecurityHeadersMiddleware(BaseHTTPMiddleware):
|
||||
async def dispatch(self, request: Request, call_next):
|
||||
response: Response = await call_next(request)
|
||||
|
||||
# Security headers
|
||||
response.headers["X-Content-Type-Options"] = "nosniff"
|
||||
response.headers["X-XSS-Protection"] = "1; mode=block"
|
||||
response.headers["Content-Security-Policy"] = "frame-ancestors *"
|
||||
|
||||
# CORS headers
|
||||
response.headers["Access-Control-Allow-Origin"] = os.getenv(
|
||||
"APP_CORS_ORIGINS",
|
||||
"http://localhost:3000"
|
||||
)
|
||||
response.headers["Access-Control-Allow-Methods"] = "GET, POST, PUT, DELETE, OPTIONS"
|
||||
response.headers["Access-Control-Allow-Headers"] = "Authorization, Content-Type"
|
||||
|
||||
return response
|
||||
|
||||
app.add_middleware(SecurityHeadersMiddleware)
|
||||
|
||||
|
||||
def add_cors_middleware(app: FastAPI):
|
||||
"""Add CORS middleware."""
|
||||
|
||||
cors_origins = os.getenv("APP_CORS_ORIGINS", "http://localhost:3000").split(",")
|
||||
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=cors_origins,
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
@@ -0,0 +1,190 @@
|
||||
"""Client for interacting with the common platform API."""
|
||||
|
||||
import httpx
|
||||
from typing import Optional, List, Dict, Any
|
||||
from request_app.settings import get_settings
|
||||
from request_app.core.logging import logger
|
||||
|
||||
|
||||
class PlatformUser:
|
||||
"""Wrapper for user data from the platform."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
id: int,
|
||||
email: str,
|
||||
first_name: str = "",
|
||||
last_name: str = "",
|
||||
is_active: bool = True,
|
||||
roles: Optional[List[str]] = None,
|
||||
):
|
||||
self.id = id
|
||||
self.email = email
|
||||
self.first_name = first_name
|
||||
self.last_name = last_name
|
||||
self.is_active = is_active
|
||||
self.roles = roles or []
|
||||
|
||||
@property
|
||||
def display_name(self) -> str:
|
||||
if self.first_name or self.last_name:
|
||||
return f"{self.first_name} {self.last_name}".strip()
|
||||
return self.email
|
||||
|
||||
def has_role(self, role_name: str) -> bool:
|
||||
return role_name in self.roles
|
||||
|
||||
def to_dict(self) -> Dict[str, Any]:
|
||||
return {
|
||||
"id": self.id,
|
||||
"email": self.email,
|
||||
"first_name": self.first_name,
|
||||
"last_name": self.last_name,
|
||||
"is_active": self.is_active,
|
||||
"roles": self.roles,
|
||||
}
|
||||
|
||||
|
||||
class PlatformClient:
|
||||
"""Client for the common platform REST API."""
|
||||
|
||||
def __init__(self):
|
||||
settings = get_settings()
|
||||
self.base_url = settings.PLATFORM_API_URL.rstrip("/")
|
||||
self.api_key = settings.PLATFORM_API_KEY
|
||||
self.timeout = 10.0
|
||||
|
||||
def _get_headers(self, token: Optional[str] = None) -> Dict[str, str]:
|
||||
headers = {"Content-Type": "application/json"}
|
||||
if self.api_key:
|
||||
headers["X-API-Key"] = self.api_key
|
||||
if token:
|
||||
headers["Authorization"] = f"Bearer {token}"
|
||||
return headers
|
||||
|
||||
async def validate_token(self, token: str) -> Optional[PlatformUser]:
|
||||
"""Validate JWT token with the platform and return user data."""
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=self.timeout) as client:
|
||||
response = await client.post(
|
||||
f"{self.base_url}/api/v1/auth/validate",
|
||||
headers=self._get_headers(token),
|
||||
)
|
||||
if response.status_code == 200:
|
||||
data = response.json()
|
||||
return PlatformUser(
|
||||
id=data["user_id"],
|
||||
email=data.get("email", ""),
|
||||
first_name=data.get("first_name", ""),
|
||||
last_name=data.get("last_name", ""),
|
||||
is_active=data.get("is_active", True),
|
||||
roles=data.get("roles", []),
|
||||
)
|
||||
logger.warning(f"Token validation failed: {response.status_code}")
|
||||
return None
|
||||
except Exception as e:
|
||||
logger.error(f"Platform token validation error: {e}")
|
||||
return None
|
||||
|
||||
async def get_user_info(self, user_id: int) -> Optional[PlatformUser]:
|
||||
"""Get user information from the platform."""
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=self.timeout) as client:
|
||||
response = await client.get(
|
||||
f"{self.base_url}/api/v1/users/{user_id}",
|
||||
headers=self._get_headers(),
|
||||
)
|
||||
if response.status_code == 200:
|
||||
data = response.json()
|
||||
return PlatformUser(
|
||||
id=data["id"],
|
||||
email=data.get("email", ""),
|
||||
first_name=data.get("first_name", ""),
|
||||
last_name=data.get("last_name", ""),
|
||||
is_active=data.get("is_active", True),
|
||||
roles=data.get("roles", []),
|
||||
)
|
||||
logger.warning(f"Get user info failed: {response.status_code}")
|
||||
return None
|
||||
except Exception as e:
|
||||
logger.error(f"Platform get user error: {e}")
|
||||
return None
|
||||
|
||||
async def get_user_roles(self, user_id: int) -> List[str]:
|
||||
"""Get user roles from the platform."""
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=self.timeout) as client:
|
||||
response = await client.get(
|
||||
f"{self.base_url}/api/v1/users/{user_id}/roles",
|
||||
headers=self._get_headers(),
|
||||
)
|
||||
if response.status_code == 200:
|
||||
data = response.json()
|
||||
return data.get("roles", [])
|
||||
return []
|
||||
except Exception as e:
|
||||
logger.error(f"Platform get user roles error: {e}")
|
||||
return []
|
||||
|
||||
async def get_users(
|
||||
self, page: int = 1, page_size: int = 100, search: Optional[str] = None
|
||||
) -> Dict[str, Any]:
|
||||
"""Get paginated list of users from the platform."""
|
||||
try:
|
||||
params = {"page": page, "page_size": page_size}
|
||||
if search:
|
||||
params["search"] = search
|
||||
|
||||
async with httpx.AsyncClient(timeout=self.timeout) as client:
|
||||
response = await client.get(
|
||||
f"{self.base_url}/api/v1/users",
|
||||
headers=self._get_headers(),
|
||||
params=params,
|
||||
)
|
||||
if response.status_code == 200:
|
||||
data = response.json()
|
||||
users = [
|
||||
PlatformUser(
|
||||
id=u["id"],
|
||||
email=u.get("email", ""),
|
||||
first_name=u.get("first_name", ""),
|
||||
last_name=u.get("last_name", ""),
|
||||
is_active=u.get("is_active", True),
|
||||
roles=u.get("roles", []),
|
||||
)
|
||||
for u in data.get("users", [])
|
||||
]
|
||||
return {
|
||||
"users": users,
|
||||
"total": data.get("total", 0),
|
||||
}
|
||||
return {"users": [], "total": 0}
|
||||
except Exception as e:
|
||||
logger.error(f"Platform get users error: {e}")
|
||||
return {"users": [], "total": 0}
|
||||
|
||||
async def check_permission(self, user_id: int, permission: str) -> bool:
|
||||
"""Check if user has a specific permission on the platform."""
|
||||
try:
|
||||
async with httpx.AsyncClient(timeout=self.timeout) as client:
|
||||
response = await client.get(
|
||||
f"{self.base_url}/api/v1/users/{user_id}/permissions/{permission}",
|
||||
headers=self._get_headers(),
|
||||
)
|
||||
return response.status_code == 200 and response.json().get(
|
||||
"allowed", False
|
||||
)
|
||||
except Exception as e:
|
||||
logger.error(f"Platform check permission error: {e}")
|
||||
return False
|
||||
|
||||
|
||||
_platform_client: Optional[PlatformClient] = None
|
||||
|
||||
|
||||
def get_platform_client() -> PlatformClient:
|
||||
"""Get or create the platform client singleton."""
|
||||
global _platform_client
|
||||
if _platform_client is None:
|
||||
_platform_client = PlatformClient()
|
||||
return _platform_client
|
||||
@@ -0,0 +1,75 @@
|
||||
"""Core module for security and authentication utilities."""
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Optional, Dict, Any
|
||||
from jose import JWTError, jwt
|
||||
import bcrypt
|
||||
from request_app.settings import get_settings
|
||||
|
||||
|
||||
def get_password_hash(password: str) -> str:
|
||||
"""Hash a password."""
|
||||
return bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt()).decode("utf-8")
|
||||
|
||||
|
||||
def verify_password(plain: str, hashed: str) -> bool:
|
||||
"""Verify a password against its hash."""
|
||||
try:
|
||||
return bcrypt.checkpw(plain.encode("utf-8"), hashed.encode("utf-8"))
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def create_local_token(user_id: int, email: str) -> str:
|
||||
"""Create a local JWT token for standalone mode."""
|
||||
settings = get_settings()
|
||||
expire = datetime.utcnow() + timedelta(minutes=settings.JWT_ACCESS_TOKEN_EXPIRE_MINUTES)
|
||||
payload = {"sub": str(user_id), "email": email, "exp": expire}
|
||||
return jwt.encode(payload, settings.JWT_SECRET_KEY, algorithm=settings.JWT_ALGORITHM)
|
||||
|
||||
|
||||
def decode_platform_token(token: str) -> Optional[Dict[str, Any]]:
|
||||
"""Decode and verify a JWT token (from platform or local)."""
|
||||
settings = get_settings()
|
||||
|
||||
# Try platform key first
|
||||
if settings.PLATFORM_JWT_PUBLIC_KEY:
|
||||
try:
|
||||
return jwt.decode(
|
||||
token,
|
||||
settings.PLATFORM_JWT_PUBLIC_KEY,
|
||||
algorithms=[settings.PLATFORM_JWT_ALGORITHM],
|
||||
)
|
||||
except JWTError:
|
||||
pass
|
||||
|
||||
# Try local key
|
||||
try:
|
||||
return jwt.decode(
|
||||
token,
|
||||
settings.JWT_SECRET_KEY,
|
||||
algorithms=[settings.JWT_ALGORITHM],
|
||||
)
|
||||
except JWTError:
|
||||
return None
|
||||
|
||||
|
||||
def get_user_id_from_token(token: str) -> int:
|
||||
"""Extract user ID from platform JWT token."""
|
||||
payload = decode_platform_token(token)
|
||||
if not payload:
|
||||
raise ValueError("Invalid token")
|
||||
|
||||
user_id = payload.get("sub")
|
||||
if not user_id:
|
||||
raise ValueError("Invalid token: missing 'sub' claim")
|
||||
|
||||
return int(user_id)
|
||||
|
||||
|
||||
def get_roles_from_token(token: str) -> list:
|
||||
"""Extract roles from platform JWT token."""
|
||||
payload = decode_platform_token(token)
|
||||
if not payload:
|
||||
return []
|
||||
return payload.get("roles", [])
|
||||
@@ -0,0 +1,9 @@
|
||||
"""Integrations package."""
|
||||
|
||||
from request_app.integrations.email import EmailClient
|
||||
from request_app.integrations.sms import SMSClient
|
||||
|
||||
__all__ = [
|
||||
"EmailClient",
|
||||
"SMSClient",
|
||||
]
|
||||
@@ -0,0 +1,297 @@
|
||||
"""Email client for SMTP and IMAP."""
|
||||
|
||||
import smtplib
|
||||
import ssl
|
||||
from email.message import EmailMessage
|
||||
from email.utils import parsedate_to_datetime
|
||||
from typing import Optional, List, Tuple
|
||||
import imaplib
|
||||
from email.header import decode_header
|
||||
from request_app.settings import get_settings
|
||||
from request_app.core.logging import email_logger
|
||||
|
||||
|
||||
class EmailClient:
|
||||
"""Email client for sending and receiving emails."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
smtp_server: Optional[str] = None,
|
||||
smtp_port: Optional[int] = None,
|
||||
username: Optional[str] = None,
|
||||
password: Optional[str] = None,
|
||||
use_tls: bool = True,
|
||||
from_email: Optional[str] = None,
|
||||
db_session=None
|
||||
):
|
||||
"""Initialize email client."""
|
||||
# Try to load from database first
|
||||
if db_session:
|
||||
from request_app.services.settings_service import SettingsService
|
||||
settings_service = SettingsService(db_session)
|
||||
db_settings = settings_service.get_email_settings()
|
||||
|
||||
self.smtp_server = smtp_server or db_settings.get('smtp_server') or get_settings().SMTP_SERVER
|
||||
self.smtp_port = smtp_port or int(db_settings.get('smtp_port', 465)) or get_settings().SMTP_PORT
|
||||
self.username = username or db_settings.get('smtp_username') or get_settings().SMTP_USERNAME
|
||||
self.password = password or db_settings.get('smtp_password') or get_settings().SMTP_PASSWORD
|
||||
self.use_tls = use_tls if db_settings.get('use_tls', 'true') == 'true' else False
|
||||
self.from_email = from_email or db_settings.get('email_from') or self.username
|
||||
self.imap_server = db_settings.get('imap_server') or get_settings().IMAP_SERVER
|
||||
self.imap_port = int(db_settings.get('imap_port', 993) or 993)
|
||||
else:
|
||||
settings = get_settings()
|
||||
self.smtp_server = smtp_server or settings.SMTP_SERVER
|
||||
self.smtp_port = smtp_port or settings.SMTP_PORT
|
||||
self.username = username or settings.SMTP_USERNAME
|
||||
self.password = password or settings.SMTP_PASSWORD
|
||||
self.use_tls = use_tls
|
||||
self.from_email = from_email or settings.EMAIL_FROM or self.username
|
||||
self.imap_server = settings.IMAP_SERVER
|
||||
self.imap_port = settings.IMAP_PORT
|
||||
|
||||
email_logger.info(f"EmailClient initialized: server={self.smtp_server}:{self.smtp_port}, user={self.username}")
|
||||
|
||||
def send_email(
|
||||
self,
|
||||
to: str,
|
||||
subject: str,
|
||||
body: str,
|
||||
html_body: Optional[str] = None,
|
||||
cc: Optional[List[str]] = None,
|
||||
bcc: Optional[List[str]] = None,
|
||||
attachments: Optional[List[dict]] = None
|
||||
) -> dict:
|
||||
"""Send an email."""
|
||||
email_logger.info(f"Sending email to={to}, subject='{subject}'")
|
||||
email_logger.debug(f"SMTP config: server={self.smtp_server}:{self.smtp_port}, tls={self.use_tls}")
|
||||
|
||||
msg = EmailMessage()
|
||||
msg["to"] = to
|
||||
msg["from"] = self.from_email
|
||||
msg["subject"] = subject
|
||||
msg.set_content(body)
|
||||
|
||||
if html_body:
|
||||
msg.add_alternative(html_body, subtype="html")
|
||||
|
||||
if cc:
|
||||
msg["cc"] = ", ".join(cc)
|
||||
email_logger.debug(f"CC: {cc}")
|
||||
|
||||
if bcc:
|
||||
msg["Bcc"] = ", ".join(bcc)
|
||||
email_logger.debug(f"BCC: {bcc}")
|
||||
|
||||
try:
|
||||
context = ssl.create_default_context() if self.use_tls else None
|
||||
|
||||
email_logger.debug(f"Connecting to SMTP server {self.smtp_server}:{self.smtp_port}...")
|
||||
|
||||
with smtplib.SMTP_SSL(self.smtp_server, self.smtp_port, context=context) as server:
|
||||
email_logger.debug("Connected. Logging in...")
|
||||
server.login(self.username, self.password)
|
||||
email_logger.debug("Logged in. Sending message...")
|
||||
server.send_message(msg)
|
||||
|
||||
email_logger.info(f"Email sent successfully to {to}")
|
||||
return {"status": "success", "message": "Email sent successfully"}
|
||||
|
||||
except smtplib.SMTPAuthenticationError as e:
|
||||
email_logger.error(f"SMTP authentication failed: {e}")
|
||||
return {"status": "error", "error": f"Authentication failed: {str(e)}"}
|
||||
except smtplib.SMTPConnectError as e:
|
||||
email_logger.error(f"SMTP connection failed: {e}")
|
||||
return {"status": "error", "error": f"Connection failed: {str(e)}"}
|
||||
except smtplib.SMTPException as e:
|
||||
email_logger.error(f"SMTP error: {e}")
|
||||
return {"status": "error", "error": f"SMTP error: {str(e)}"}
|
||||
except Exception as e:
|
||||
email_logger.error(f"Unexpected error sending email: {e}", exc_info=True)
|
||||
return {"status": "error", "error": str(e)}
|
||||
|
||||
def send_html_template(
|
||||
self,
|
||||
to: str,
|
||||
subject: str,
|
||||
template_path: str,
|
||||
**kwargs
|
||||
) -> dict:
|
||||
"""Send email with HTML template."""
|
||||
try:
|
||||
with open(template_path, 'r', encoding='utf-8') as f:
|
||||
html_body = f.read().format(**kwargs)
|
||||
|
||||
return self.send_email(
|
||||
to=to,
|
||||
subject=subject,
|
||||
body="",
|
||||
html_body=html_body
|
||||
)
|
||||
|
||||
except Exception as e:
|
||||
email_logger.error(f"Template error: {e}", exc_info=True)
|
||||
return {"status": "error", "error": f"Template error: {str(e)}"}
|
||||
|
||||
def test_connection(self) -> dict:
|
||||
"""Test SMTP connection."""
|
||||
email_logger.info(f"Testing SMTP connection to {self.smtp_server}:{self.smtp_port}")
|
||||
|
||||
try:
|
||||
context = ssl.create_default_context() if self.use_tls else None
|
||||
|
||||
with smtplib.SMTP_SSL(self.smtp_server, self.smtp_port, context=context) as server:
|
||||
server.login(self.username, self.password)
|
||||
|
||||
email_logger.info("SMTP connection test successful")
|
||||
return {"status": "success", "message": "Connection successful"}
|
||||
|
||||
except Exception as e:
|
||||
email_logger.error(f"SMTP connection test failed: {e}", exc_info=True)
|
||||
return {"status": "error", "error": str(e)}
|
||||
|
||||
def fetch_emails(self, folder: str = "INBOX", mark_seen: bool = True, delete_after: bool = False) -> List[dict]:
|
||||
"""Fetch unread emails from IMAP server.
|
||||
|
||||
Args:
|
||||
folder: IMAP folder to fetch from.
|
||||
mark_seen: Mark emails as seen after fetching.
|
||||
delete_after: Delete emails from server after successful fetch.
|
||||
|
||||
Returns a list of dicts with keys: message_id, in_reply_to, from, to,
|
||||
subject, body_text, body_html, date, references.
|
||||
"""
|
||||
email_logger.info(f"Fetching emails from {self.imap_server}:{self.imap_port}, folder={folder}, delete_after={delete_after}")
|
||||
emails = []
|
||||
fetched_nums = []
|
||||
|
||||
try:
|
||||
context = ssl.create_default_context()
|
||||
mail = imaplib.IMAP4_SSL(self.imap_server, self.imap_port, ssl_context=context)
|
||||
mail.login(self.username, self.password)
|
||||
mail.select(folder, readonly=False)
|
||||
|
||||
status, data = mail.search(None, "ALL")
|
||||
if status != "OK":
|
||||
email_logger.warning(f"IMAP search failed: {status}")
|
||||
mail.logout()
|
||||
return emails
|
||||
|
||||
msg_nums = data[0].split() if data[0] else []
|
||||
email_logger.info(f"Found {len(msg_nums)} emails in {folder}")
|
||||
|
||||
for num in msg_nums:
|
||||
try:
|
||||
fetch_flag = "(RFC822)" if mark_seen else "(BODY.PEEK[])"
|
||||
status, msg_data = mail.fetch(num, fetch_flag)
|
||||
if status != "OK":
|
||||
continue
|
||||
|
||||
raw_email = msg_data[0][1]
|
||||
import email as email_module
|
||||
msg = email_module.message_from_bytes(raw_email)
|
||||
|
||||
parsed = self._parse_email(msg)
|
||||
emails.append(parsed)
|
||||
fetched_nums.append(num)
|
||||
except Exception as e:
|
||||
email_logger.error(f"Error parsing email {num}: {e}")
|
||||
|
||||
# Delete fetched emails from server if requested
|
||||
if delete_after and fetched_nums:
|
||||
for num in fetched_nums:
|
||||
try:
|
||||
mail.store(num, "+FLAGS", "\\Deleted")
|
||||
except Exception as e:
|
||||
email_logger.error(f"Error marking email {num} for deletion: {e}")
|
||||
mail.expunge()
|
||||
email_logger.info(f"Deleted {len(fetched_nums)} emails from server")
|
||||
|
||||
mail.logout()
|
||||
email_logger.info(f"Fetched {len(emails)} emails")
|
||||
|
||||
except imaplib.IMAP4.error as e:
|
||||
email_logger.error(f"IMAP error: {e}")
|
||||
except Exception as e:
|
||||
email_logger.error(f"Fetch emails error: {e}", exc_info=True)
|
||||
|
||||
return emails
|
||||
|
||||
def _parse_email(self, msg) -> dict:
|
||||
"""Parse an email.message.Message into a dict."""
|
||||
from email import message_from_bytes
|
||||
|
||||
message_id = msg.get("Message-ID", "")
|
||||
in_reply_to = msg.get("In-Reply-To", "")
|
||||
references = msg.get("References", "")
|
||||
from_addr = self._decode_header(msg.get("From", ""))
|
||||
to_addr = self._decode_header(msg.get("To", ""))
|
||||
subject = self._decode_header(msg.get("Subject", ""))
|
||||
date_str = msg.get("Date", "")
|
||||
|
||||
date = None
|
||||
if date_str:
|
||||
try:
|
||||
date = parsedate_to_datetime(date_str)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
body_text = ""
|
||||
body_html = ""
|
||||
|
||||
if msg.is_multipart():
|
||||
for part in msg.walk():
|
||||
content_type = part.get_content_type()
|
||||
disposition = str(part.get("Content-Disposition", ""))
|
||||
if "attachment" in disposition:
|
||||
continue
|
||||
payload = part.get_payload(decode=True)
|
||||
if payload is None:
|
||||
continue
|
||||
charset = part.get_content_charset() or "utf-8"
|
||||
try:
|
||||
text = payload.decode(charset, errors="replace")
|
||||
except Exception:
|
||||
text = payload.decode("utf-8", errors="replace")
|
||||
if content_type == "text/plain":
|
||||
body_text += text
|
||||
elif content_type == "text/html":
|
||||
body_html += text
|
||||
else:
|
||||
payload = msg.get_payload(decode=True)
|
||||
if payload:
|
||||
charset = msg.get_content_charset() or "utf-8"
|
||||
try:
|
||||
text = payload.decode(charset, errors="replace")
|
||||
except Exception:
|
||||
text = payload.decode("utf-8", errors="replace")
|
||||
if msg.get_content_type() == "text/html":
|
||||
body_html = text
|
||||
else:
|
||||
body_text = text
|
||||
|
||||
return {
|
||||
"message_id": message_id,
|
||||
"in_reply_to": in_reply_to,
|
||||
"references": references,
|
||||
"from": from_addr,
|
||||
"to": to_addr,
|
||||
"subject": subject,
|
||||
"body_text": body_text,
|
||||
"body_html": body_html,
|
||||
"date": date,
|
||||
}
|
||||
|
||||
@staticmethod
|
||||
def _decode_header(header: str) -> str:
|
||||
"""Decode RFC2047 encoded header."""
|
||||
if not header:
|
||||
return ""
|
||||
decoded_parts = decode_header(header)
|
||||
result = []
|
||||
for part, charset in decoded_parts:
|
||||
if isinstance(part, bytes):
|
||||
result.append(part.decode(charset or "utf-8", errors="replace"))
|
||||
else:
|
||||
result.append(part)
|
||||
return " ".join(result)
|
||||
@@ -0,0 +1,110 @@
|
||||
"""SMS client for Twilio integration."""
|
||||
|
||||
from twilio.rest import Client
|
||||
from typing import Optional, List
|
||||
from request_app.settings import get_settings
|
||||
from request_app.core.logging import sms_logger
|
||||
|
||||
|
||||
class SMSClient:
|
||||
"""SMS client for Twilio integration."""
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
account_sid: Optional[str] = None,
|
||||
auth_token: Optional[str] = None,
|
||||
from_number: Optional[str] = None,
|
||||
db_session=None
|
||||
):
|
||||
"""Initialize SMS client."""
|
||||
# Try to load from database first
|
||||
if db_session:
|
||||
from request_app.services.settings_service import SettingsService
|
||||
settings_service = SettingsService(db_session)
|
||||
db_settings = settings_service.get_sms_settings()
|
||||
|
||||
self.account_sid = account_sid or db_settings.get('twilio_account_sid') or get_settings().TWILIO_ACCOUNT_SID
|
||||
self.auth_token = auth_token or db_settings.get('twilio_auth_token') or get_settings().TWILIO_AUTH_TOKEN
|
||||
self.from_number = from_number or db_settings.get('twilio_from_number') or get_settings().TWILIO_FROM_NUMBER
|
||||
else:
|
||||
settings = get_settings()
|
||||
self.account_sid = account_sid or settings.TWILIO_ACCOUNT_SID
|
||||
self.auth_token = auth_token or settings.TWILIO_AUTH_TOKEN
|
||||
self.from_number = from_number or settings.TWILIO_FROM_NUMBER
|
||||
|
||||
if not self.account_sid or not self.auth_token:
|
||||
sms_logger.warning("Twilio credentials not configured")
|
||||
raise ValueError("Twilio credentials not configured")
|
||||
|
||||
sms_logger.info(f"SMSClient initialized: sid={self.account_sid[:10]}..., from={self.from_number}")
|
||||
self.client = Client(self.account_sid, self.auth_token)
|
||||
|
||||
def send_sms(
|
||||
self,
|
||||
to: str,
|
||||
message: str
|
||||
) -> dict:
|
||||
"""Send an SMS message."""
|
||||
sms_logger.info(f"Sending SMS to={to}, message_length={len(message)}")
|
||||
sms_logger.debug(f"SMS content: {message[:100]}...")
|
||||
|
||||
try:
|
||||
message_obj = self.client.messages.create(
|
||||
to=to,
|
||||
from_=self.from_number,
|
||||
body=message
|
||||
)
|
||||
|
||||
sms_logger.info(f"SMS sent successfully: sid={message_obj.sid}")
|
||||
return {
|
||||
"status": "success",
|
||||
"sid": message_obj.sid,
|
||||
"price": message_obj.price,
|
||||
"direction": message_obj.direction
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
sms_logger.error(f"Error sending SMS to {to}: {e}", exc_info=True)
|
||||
return {
|
||||
"status": "error",
|
||||
"error": str(e),
|
||||
"error_type": type(e).__name__
|
||||
}
|
||||
|
||||
def send_template_sms(
|
||||
self,
|
||||
to: str,
|
||||
template_name: str,
|
||||
**kwargs
|
||||
) -> dict:
|
||||
"""Send SMS from template."""
|
||||
SMS_TEMPLATES = {
|
||||
"verification": "Ваш код подтверждения: {code}. Действителен 10 минут.",
|
||||
"ticket_created": "Тикет #{ticket_id} создан. Приоритет: {priority}. Статус: {status}",
|
||||
"ticket_updated": "Тикет #{ticket_id} обновлен. {changes}",
|
||||
"reminder": "Напоминание: тикет #{ticket_id} ожидает решения"
|
||||
}
|
||||
|
||||
if template_name not in SMS_TEMPLATES:
|
||||
sms_logger.error(f"Template '{template_name}' not found")
|
||||
return {
|
||||
"status": "error",
|
||||
"error": f"Template '{template_name}' not found"
|
||||
}
|
||||
|
||||
message = SMS_TEMPLATES[template_name].format(**kwargs)
|
||||
return self.send_sms(to, message)
|
||||
|
||||
def send_bulk_sms(
|
||||
self,
|
||||
recipients: List[str],
|
||||
message: str
|
||||
) -> List[dict]:
|
||||
"""Send SMS to multiple recipients."""
|
||||
sms_logger.info(f"Sending bulk SMS to {len(recipients)} recipients")
|
||||
results = []
|
||||
for recipient in recipients:
|
||||
result = self.send_sms(recipient, message)
|
||||
result["recipient"] = recipient
|
||||
results.append(result)
|
||||
return results
|
||||
@@ -0,0 +1,279 @@
|
||||
"""Service Request System - Main Application."""
|
||||
|
||||
import os
|
||||
from pathlib import Path
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.staticfiles import StaticFiles
|
||||
from fastapi.responses import FileResponse, JSONResponse, HTMLResponse
|
||||
from apscheduler.schedulers.background import BackgroundScheduler
|
||||
from request_app.settings import get_settings
|
||||
from request_app.core.database import init_db, engine, Base, SessionLocal
|
||||
from request_app.core.middleware import add_security_headers, add_cors_middleware
|
||||
from request_app.core.exception_handlers import app_exception_handler
|
||||
from request_app.core.exceptions import AppException
|
||||
from request_app.core.logging import setup_logging, logger
|
||||
from request_app.api.v1.routes import tickets, users, auth, health, reference, notifications, emails, settings, notification_templates
|
||||
|
||||
# Setup logging
|
||||
setup_logging()
|
||||
|
||||
# Background scheduler for periodic tasks
|
||||
scheduler = BackgroundScheduler()
|
||||
|
||||
# Frontend build directory
|
||||
FRONTEND_DIR = Path(__file__).parent.parent / "frontend" / "dist"
|
||||
|
||||
# Create FastAPI app
|
||||
app = FastAPI(
|
||||
title=get_settings().APP_NAME,
|
||||
version=get_settings().APP_VERSION,
|
||||
description="Service Request System - ITSM Platform",
|
||||
docs_url=None,
|
||||
redoc_url=None,
|
||||
openapi_url="/openapi.json"
|
||||
)
|
||||
|
||||
|
||||
@app.get("/docs", include_in_schema=False)
|
||||
async def custom_swagger_ui_html():
|
||||
"""Swagger UI with local fallback."""
|
||||
return HTMLResponse("""
|
||||
<!DOCTYPE html>
|
||||
<html><head>
|
||||
<meta charset="utf-8">
|
||||
<title>Service Request System - Swagger UI</title>
|
||||
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5.9.0/swagger-ui.css">
|
||||
</head><body>
|
||||
<div id="swagger-ui"></div>
|
||||
<script src="https://cdn.jsdelivr.net/npm/swagger-ui-dist@5.9.0/swagger-ui-bundle.js"></script>
|
||||
<script>
|
||||
window.onload = function() {
|
||||
try {
|
||||
SwaggerUIBundle({
|
||||
url: "/openapi.json",
|
||||
dom_id: "#swagger-ui",
|
||||
presets: [SwaggerUIBundle.presets.apis, SwaggerUIBundle.SwaggerUIStandalonePreset],
|
||||
layout: "BaseLayout"
|
||||
});
|
||||
} catch(e) {
|
||||
document.getElementById("swagger-ui").innerHTML =
|
||||
"<h2>Ошибка загрузки Swagger UI</h2><p>" + e.message + "</p>" +
|
||||
"<p>Попробуйте обновить страницу или проверьте подключение к интернету (нужен доступ к CDN).</p>" +
|
||||
"<p><a href='/openapi.json'>Скачать OpenAPI JSON</a></p>";
|
||||
}
|
||||
};
|
||||
</script>
|
||||
</body></html>
|
||||
""")
|
||||
|
||||
# Add CORS middleware
|
||||
add_cors_middleware(app)
|
||||
|
||||
# Add security headers
|
||||
add_security_headers(app)
|
||||
|
||||
# Include routers
|
||||
app.include_router(health.router, prefix="/api/v1")
|
||||
app.include_router(auth.router, prefix="/api/v1/auth")
|
||||
app.include_router(users.router, prefix="/api/v1/users")
|
||||
app.include_router(tickets.router, prefix="/api/v1")
|
||||
app.include_router(reference.router, prefix="/api/v1")
|
||||
app.include_router(notifications.router, prefix="/api/v1")
|
||||
app.include_router(emails.router, prefix="/api/v1")
|
||||
app.include_router(settings.router, prefix="/api/v1")
|
||||
app.include_router(notification_templates.router, prefix="/api/v1")
|
||||
|
||||
# Exception handlers
|
||||
app.add_exception_handler(AppException, app_exception_handler)
|
||||
|
||||
# Serve frontend static files
|
||||
if FRONTEND_DIR.exists():
|
||||
app.mount("/assets", StaticFiles(directory=str(FRONTEND_DIR / "assets")), name="assets")
|
||||
|
||||
@app.get("/")
|
||||
async def serve_root():
|
||||
return FileResponse(str(FRONTEND_DIR / "index.html"))
|
||||
|
||||
# SPA routes - serve index.html for client-side routing
|
||||
@app.get("/login")
|
||||
@app.get("/tickets")
|
||||
@app.get("/tickets/new")
|
||||
@app.get("/tickets/{ticket_id}")
|
||||
@app.get("/tickets/{ticket_id}/{path:path}")
|
||||
@app.get("/users")
|
||||
@app.get("/users/new")
|
||||
@app.get("/users/{user_id}")
|
||||
@app.get("/reference")
|
||||
@app.get("/settings")
|
||||
@app.get("/templates")
|
||||
async def serve_spa():
|
||||
return FileResponse(str(FRONTEND_DIR / "index.html"))
|
||||
|
||||
# Static files (favicon, etc.)
|
||||
@app.get("/vite.svg")
|
||||
async def serve_vite_svg():
|
||||
file_path = FRONTEND_DIR / "vite.svg"
|
||||
if file_path.is_file():
|
||||
return FileResponse(str(file_path))
|
||||
return JSONResponse({"detail": "Not Found"}, status_code=404)
|
||||
|
||||
|
||||
# --- TEST ONLY:简易登录页面 ---
|
||||
@app.get("/test-login")
|
||||
async def test_login_page():
|
||||
"""Test login page - generates a JWT token for testing."""
|
||||
from jose import jwt
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
payload = {
|
||||
"sub": "1",
|
||||
"email": "admin@company.com",
|
||||
"first_name": "Админ",
|
||||
"last_name": "Тестов",
|
||||
"is_active": True,
|
||||
"roles": ["admin", "support_agent"],
|
||||
"exp": datetime.utcnow() + timedelta(hours=24),
|
||||
}
|
||||
token = jwt.encode(
|
||||
payload,
|
||||
get_settings().JWT_SECRET_KEY,
|
||||
algorithm=get_settings().JWT_ALGORITHM,
|
||||
)
|
||||
|
||||
html = f"""<!DOCTYPE html>
|
||||
<html><head><meta charset="utf-8"><title>Test Login</title>
|
||||
<style>
|
||||
body {{ font-family: system-ui; display: flex; justify-content: center; align-items: center; height: 100vh; margin: 0; background: #f3f4f6; }}
|
||||
.card {{ background: white; padding: 2rem; border-radius: 12px; box-shadow: 0 2px 8px rgba(0,0,0,0.1); text-align: center; max-width: 400px; }}
|
||||
h1 {{ margin: 0 0 0.5rem; }}
|
||||
p {{ color: #666; margin: 0 0 1.5rem; }}
|
||||
a {{ display: inline-block; padding: 12px 32px; background: #2563eb; color: white; text-decoration: none; border-radius: 8px; font-weight: 500; }}
|
||||
a:hover {{ background: #1d4ed8; }}
|
||||
.token {{ background: #f9fafb; padding: 8px; border-radius: 6px; font-size: 11px; word-break: break-all; margin: 1rem 0; color: #666; }}
|
||||
</style></head><body>
|
||||
<div class="card">
|
||||
<h1>Service Desk</h1>
|
||||
<p>Тестовый вход выполнен</p>
|
||||
<p style="font-size:14px"><b>Админ Тестов</b><br>admin@company.com<br>Роли: admin, support_agent</p>
|
||||
<a href="/?token={token}">Открыть Service Desk</a>
|
||||
<div class="token">JWT: {token[:50]}...</div>
|
||||
</div>
|
||||
</body></html>"""
|
||||
return HTMLResponse(html)
|
||||
|
||||
|
||||
@app.get("/quick-login")
|
||||
async def quick_login():
|
||||
"""Quick login - immediately redirect with token."""
|
||||
from jose import jwt
|
||||
from datetime import datetime, timedelta
|
||||
from fastapi.responses import RedirectResponse
|
||||
|
||||
payload = {
|
||||
"sub": "1",
|
||||
"email": "admin@company.com",
|
||||
"first_name": "Админ",
|
||||
"last_name": "Тестов",
|
||||
"is_active": True,
|
||||
"roles": ["admin", "support_agent"],
|
||||
"exp": datetime.utcnow() + timedelta(hours=24),
|
||||
}
|
||||
token = jwt.encode(
|
||||
payload,
|
||||
get_settings().JWT_SECRET_KEY,
|
||||
algorithm=get_settings().JWT_ALGORITHM,
|
||||
)
|
||||
return RedirectResponse(url=f"/?token={token}", status_code=302)
|
||||
# --- END TEST ---
|
||||
|
||||
|
||||
def _run_email_fetch():
|
||||
"""Background job: fetch emails from IMAP."""
|
||||
try:
|
||||
from request_app.workers.email_worker import fetch_incoming_emails
|
||||
result = fetch_incoming_emails()
|
||||
logger.info(f"Email fetch result: {result}")
|
||||
except Exception as e:
|
||||
logger.error(f"Email fetch error: {e}")
|
||||
|
||||
|
||||
def _process_outbox():
|
||||
"""Background job: try to send queued emails."""
|
||||
try:
|
||||
from request_app.services.email_outbox_service import EmailOutboxService
|
||||
db = SessionLocal()
|
||||
try:
|
||||
svc = EmailOutboxService(db)
|
||||
result = svc.process_queue()
|
||||
if result["processed"] > 0:
|
||||
logger.info(f"Outbox processed: {result}")
|
||||
finally:
|
||||
db.close()
|
||||
except Exception as e:
|
||||
logger.error(f"Outbox processing error: {e}")
|
||||
|
||||
|
||||
def _get_fetch_interval() -> int:
|
||||
"""Read fetch interval from DB (seconds)."""
|
||||
from request_app.services.settings_service import SettingsService
|
||||
db = SessionLocal()
|
||||
try:
|
||||
svc = SettingsService(db)
|
||||
return max(60, int(svc.get_setting_value("email_fetch_interval", "300")))
|
||||
except Exception:
|
||||
return 300
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
@app.on_event("startup")
|
||||
async def startup_event():
|
||||
"""Initialize database on startup."""
|
||||
init_db()
|
||||
|
||||
from request_app.services.settings_service import SettingsService
|
||||
db = SessionLocal()
|
||||
try:
|
||||
settings_service = SettingsService(db)
|
||||
settings_service.initialize_defaults()
|
||||
logger.info("Settings initialized")
|
||||
except Exception as e:
|
||||
logger.error(f"Settings initialization error: {e}")
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
# Start background schedulers
|
||||
interval = _get_fetch_interval()
|
||||
scheduler.add_job(_run_email_fetch, "interval", seconds=interval, id="email_fetch", replace_existing=True)
|
||||
scheduler.add_job(_process_outbox, "interval", seconds=120, id="email_outbox", replace_existing=True)
|
||||
scheduler.start()
|
||||
logger.info(f"Schedulers started: email_fetch({interval}s), outbox(120s)")
|
||||
|
||||
logger.info("Database initialized successfully!")
|
||||
if FRONTEND_DIR.exists():
|
||||
logger.info(f"Frontend served from: {FRONTEND_DIR}")
|
||||
|
||||
|
||||
@app.on_event("shutdown")
|
||||
async def shutdown_event():
|
||||
"""Cleanup on shutdown."""
|
||||
scheduler.shutdown(wait=False)
|
||||
logger.info("Application shutting down...")
|
||||
|
||||
|
||||
def reschedule_email_fetch():
|
||||
"""Reschedule email fetch job with current interval from DB. Call after settings change."""
|
||||
interval = _get_fetch_interval()
|
||||
scheduler.reschedule_job("email_fetch", trigger="interval", seconds=interval)
|
||||
logger.info(f"Email fetch rescheduled (interval={interval}s)")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import uvicorn
|
||||
uvicorn.run(
|
||||
"app.main:app",
|
||||
host="0.0.0.0",
|
||||
port=8000,
|
||||
reload=get_settings().APP_DEBUG
|
||||
)
|
||||
@@ -0,0 +1,39 @@
|
||||
"""Models package."""
|
||||
|
||||
from request_app.models.base import Base, TimestampMixin
|
||||
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.ticket import Ticket
|
||||
from request_app.models.comment import Comment
|
||||
from request_app.models.notification import Notification
|
||||
from request_app.models.email_message import EmailMessage, EmailAttachment
|
||||
from request_app.models.email_outbox import EmailOutbox
|
||||
from request_app.models.ticket_event import TicketEvent
|
||||
from request_app.models.extra import Company, Location, Department, UserDepartment
|
||||
from request_app.models.setting import SystemSetting
|
||||
from request_app.models.notification_template import NotificationTemplate, SavedFilter
|
||||
|
||||
__all__ = [
|
||||
"Base",
|
||||
"TimestampMixin",
|
||||
"User",
|
||||
"Priority",
|
||||
"Status",
|
||||
"Category",
|
||||
"Ticket",
|
||||
"Comment",
|
||||
"Notification",
|
||||
"EmailMessage",
|
||||
"EmailAttachment",
|
||||
"EmailOutbox",
|
||||
"TicketEvent",
|
||||
"Company",
|
||||
"Location",
|
||||
"Department",
|
||||
"UserDepartment",
|
||||
"SystemSetting",
|
||||
"NotificationTemplate",
|
||||
"SavedFilter",
|
||||
]
|
||||
@@ -0,0 +1,14 @@
|
||||
"""Base model with common fields."""
|
||||
|
||||
from datetime import datetime
|
||||
from sqlalchemy import Column, DateTime, Integer
|
||||
from sqlalchemy.orm import declarative_base
|
||||
|
||||
Base = declarative_base()
|
||||
|
||||
|
||||
class TimestampMixin:
|
||||
"""Mixin for timestamp columns."""
|
||||
|
||||
created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
|
||||
@@ -0,0 +1,22 @@
|
||||
"""Category model."""
|
||||
|
||||
from sqlalchemy import Column, String, Integer, ForeignKey
|
||||
from sqlalchemy.orm import relationship
|
||||
from request_app.models.base import Base, TimestampMixin
|
||||
|
||||
|
||||
class Category(Base, TimestampMixin):
|
||||
"""Category model."""
|
||||
|
||||
__tablename__ = "categories"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
name = Column(String(100), unique=True, nullable=False)
|
||||
parent_id = Column(Integer, ForeignKey("categories.id", ondelete="SET NULL"))
|
||||
|
||||
# Relationships
|
||||
subcategories = relationship("Category", backref="parent", remote_side=[id])
|
||||
tickets = relationship("Ticket", back_populates="category")
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"<Category(id={self.id}, name='{self.name}')>"
|
||||
@@ -0,0 +1,23 @@
|
||||
"""Comment model."""
|
||||
|
||||
from sqlalchemy import Column, Text, DateTime, ForeignKey, Integer
|
||||
from sqlalchemy.orm import relationship
|
||||
from request_app.models.base import Base, TimestampMixin
|
||||
|
||||
|
||||
class Comment(Base, TimestampMixin):
|
||||
"""Comment model."""
|
||||
|
||||
__tablename__ = "comments"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
ticket_id = Column(Integer, ForeignKey("tickets.id", ondelete="CASCADE"), nullable=False)
|
||||
created_by = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"), nullable=False)
|
||||
comment_text = Column(Text, nullable=False)
|
||||
|
||||
# Relationships
|
||||
ticket = relationship("Ticket", back_populates="comments")
|
||||
user = relationship("User", back_populates="comments")
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"<Comment(id={self.id}, ticket_id={self.ticket_id})>"
|
||||
@@ -0,0 +1,67 @@
|
||||
"""Email message model for conversation threads."""
|
||||
|
||||
from sqlalchemy import Column, Text, DateTime, ForeignKey, Integer, String, Boolean
|
||||
from sqlalchemy.orm import relationship
|
||||
from request_app.models.base import Base, TimestampMixin
|
||||
|
||||
|
||||
class EmailMessage(Base, TimestampMixin):
|
||||
"""Email message model for ticket conversation threads."""
|
||||
|
||||
__tablename__ = "email_messages"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
ticket_id = Column(Integer, ForeignKey("tickets.id", ondelete="CASCADE"), nullable=False)
|
||||
|
||||
# Email metadata
|
||||
direction = Column(String(10), nullable=False) # 'incoming' or 'outgoing'
|
||||
message_id = Column(String(500)) # RFC 2822 Message-ID for threading
|
||||
in_reply_to = Column(String(500)) # In-Reply-To for threading
|
||||
references = Column(Text) # References header for threading
|
||||
|
||||
# Email addresses
|
||||
from_address = Column(String(500), nullable=False)
|
||||
to_addresses = Column(Text, nullable=False) # Comma-separated
|
||||
cc_addresses = Column(Text)
|
||||
|
||||
# Content
|
||||
subject = Column(String(4000))
|
||||
body_text = Column(Text) # Plain text body
|
||||
body_html = Column(Text) # HTML body
|
||||
|
||||
# Status
|
||||
is_read = Column(Boolean, default=False)
|
||||
sent_at = Column(DateTime) # When the email was actually sent
|
||||
received_at = Column(DateTime) # When the email was received
|
||||
|
||||
# User who sent the reply (for outgoing)
|
||||
sent_by = Column(Integer, ForeignKey("users.id", ondelete="SET NULL"))
|
||||
|
||||
# Relationships
|
||||
ticket = relationship("Ticket", back_populates="email_messages")
|
||||
sender = relationship("User", foreign_keys=[sent_by])
|
||||
attachments = relationship("EmailAttachment", back_populates="email_message", cascade="all, delete-orphan")
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"<EmailMessage(id={self.id}, direction='{self.direction}', subject='{self.subject}')>"
|
||||
|
||||
|
||||
class EmailAttachment(Base, TimestampMixin):
|
||||
"""Email attachment model."""
|
||||
|
||||
__tablename__ = "email_attachments"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
email_message_id = Column(Integer, ForeignKey("email_messages.id", ondelete="CASCADE"), nullable=False)
|
||||
|
||||
# File info
|
||||
filename = Column(String(500), nullable=False)
|
||||
content_type = Column(String(255))
|
||||
file_size = Column(Integer) # Size in bytes
|
||||
file_path = Column(String(1000)) # Path to stored file
|
||||
|
||||
# Relationships
|
||||
email_message = relationship("EmailMessage", back_populates="attachments")
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"<EmailAttachment(id={self.id}, filename='{self.filename}')>"
|
||||
@@ -0,0 +1,30 @@
|
||||
"""Email outbox model for send queue."""
|
||||
|
||||
from sqlalchemy import Column, Integer, String, Text, DateTime, Boolean
|
||||
from datetime import datetime
|
||||
from request_app.models.base import Base, TimestampMixin
|
||||
|
||||
|
||||
class EmailOutbox(Base, TimestampMixin):
|
||||
"""Queued emails waiting to be sent."""
|
||||
|
||||
__tablename__ = "email_outbox"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
ticket_id = Column(Integer, nullable=True)
|
||||
user_id = Column(Integer, nullable=True)
|
||||
|
||||
to_addresses = Column(Text, nullable=False)
|
||||
cc_addresses = Column(Text)
|
||||
subject = Column(String(4000))
|
||||
body_text = Column(Text)
|
||||
body_html = Column(Text)
|
||||
|
||||
status = Column(String(20), default="pending") # pending, sending, sent, failed
|
||||
retries = Column(Integer, default=0)
|
||||
max_retries = Column(Integer, default=5)
|
||||
last_error = Column(Text)
|
||||
sent_at = Column(DateTime)
|
||||
|
||||
def __repr__(self):
|
||||
return f"<EmailOutbox(id={self.id}, status='{self.status}', to='{self.to_addresses}')>"
|
||||
@@ -0,0 +1,70 @@
|
||||
"""Additional models."""
|
||||
|
||||
from sqlalchemy import Column, String, Text, Integer, ForeignKey, Boolean
|
||||
from sqlalchemy.orm import relationship
|
||||
from request_app.models.base import Base, TimestampMixin
|
||||
|
||||
|
||||
class Company(Base, TimestampMixin):
|
||||
"""Company model."""
|
||||
|
||||
__tablename__ = "companies"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
name = Column(String(255), unique=True, nullable=False)
|
||||
address = Column(Text)
|
||||
phone = Column(String(50))
|
||||
website = Column(String(255))
|
||||
|
||||
# Relationships
|
||||
tickets = relationship("Ticket", back_populates="company")
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"<Company(id={self.id}, name='{self.name}')>"
|
||||
|
||||
|
||||
class Location(Base, TimestampMixin):
|
||||
"""Location model."""
|
||||
|
||||
__tablename__ = "locations"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
name = Column(String(255), unique=True, nullable=False)
|
||||
address = Column(Text)
|
||||
phone = Column(String(50))
|
||||
|
||||
# Relationships
|
||||
tickets = relationship("Ticket", back_populates="location")
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"<Location(id={self.id}, name='{self.name}')>"
|
||||
|
||||
|
||||
class Department(Base, TimestampMixin):
|
||||
"""Department model."""
|
||||
|
||||
__tablename__ = "departments"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
name = Column(String(255), unique=True, nullable=False)
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"<Department(id={self.id}, name='{self.name}')>"
|
||||
|
||||
|
||||
class UserDepartment(Base, TimestampMixin):
|
||||
"""UserDepartment model - local department assignments."""
|
||||
|
||||
__tablename__ = "user_departments"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
user_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"), nullable=False)
|
||||
department_id = Column(Integer, ForeignKey("departments.id", ondelete="CASCADE"), nullable=False)
|
||||
is_primary = Column(Boolean, default=False)
|
||||
|
||||
# Relationships
|
||||
user = relationship("User")
|
||||
department = relationship("Department")
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"<UserDepartment(user_id={self.user_id}, department_id={self.department_id})>"
|
||||
@@ -0,0 +1,27 @@
|
||||
"""Notification model."""
|
||||
|
||||
from sqlalchemy import Column, String, Text, DateTime, ForeignKey, Integer
|
||||
from sqlalchemy.orm import relationship
|
||||
from request_app.models.base import Base, TimestampMixin
|
||||
|
||||
|
||||
class Notification(Base, TimestampMixin):
|
||||
"""Notification model."""
|
||||
|
||||
__tablename__ = "notifications"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
user_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"), nullable=False)
|
||||
ticket_id = Column(Integer, ForeignKey("tickets.id", ondelete="CASCADE"))
|
||||
type = Column(String(50), nullable=False) # email, sms, in_app
|
||||
title = Column(String(255), nullable=False)
|
||||
message = Column(Text, nullable=False)
|
||||
is_read = Column(Integer, default=0) # 0=False, 1=True
|
||||
is_delivered = Column(Integer, default=0) # 0=False, 1=True
|
||||
sent_at = Column(DateTime)
|
||||
|
||||
# Relationships
|
||||
user = relationship("User")
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"<Notification(id={self.id}, user_id={self.user_id})>"
|
||||
@@ -0,0 +1,45 @@
|
||||
"""Notification template model."""
|
||||
|
||||
from sqlalchemy import Column, String, Integer, Text, Boolean, ForeignKey
|
||||
from sqlalchemy.orm import relationship
|
||||
from request_app.models.base import Base, TimestampMixin
|
||||
|
||||
|
||||
class NotificationTemplate(Base, TimestampMixin):
|
||||
"""Notification template model."""
|
||||
|
||||
__tablename__ = "notification_templates"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
name = Column(String(100), unique=True, nullable=False, index=True)
|
||||
event_type = Column(String(50), nullable=False) # ticket_created, ticket_reopened, ticket_initiator_reply, ticket_assigned, ticket_updated, ticket_closed
|
||||
channel = Column(String(20), nullable=False) # email, sms, both
|
||||
subject_template = Column(String(500)) # For email
|
||||
body_template = Column(Text, nullable=False)
|
||||
is_active = Column(Boolean, default=True)
|
||||
send_to_initiator = Column(Boolean, default=True)
|
||||
send_to_specialist = Column(Boolean, default=True)
|
||||
send_to_group = Column(Boolean, default=False)
|
||||
department_id = Column(Integer, ForeignKey("departments.id", ondelete="SET NULL"), nullable=True)
|
||||
specialist_ids = Column(Text, nullable=True) # JSON array of user IDs for targeted specialists
|
||||
|
||||
# Relationships
|
||||
department = relationship("Department")
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"<NotificationTemplate(name='{self.name}', event='{self.event_type}')>"
|
||||
|
||||
|
||||
class SavedFilter(Base, TimestampMixin):
|
||||
"""Saved filter model for custom presets."""
|
||||
|
||||
__tablename__ = "saved_filters"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
user_id = Column(Integer, nullable=False, index=True)
|
||||
name = Column(String(100), nullable=False)
|
||||
filter_type = Column(String(20), nullable=False) # tickets, users
|
||||
filter_config = Column(Text, nullable=False) # JSON with filter params
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"<SavedFilter(name='{self.name}', user_id={self.user_id})>"
|
||||
@@ -0,0 +1,18 @@
|
||||
"""Priority model."""
|
||||
|
||||
from sqlalchemy import Column, String, Integer
|
||||
from request_app.models.base import Base, TimestampMixin
|
||||
|
||||
|
||||
class Priority(Base, TimestampMixin):
|
||||
"""Priority model."""
|
||||
|
||||
__tablename__ = "priorities"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
name = Column(String(50), unique=True, nullable=False)
|
||||
level = Column(Integer, nullable=False) # 1=Low, 2=Medium, 3=High, 4=Critical
|
||||
default_response_time_minutes = Column(Integer, default=60)
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"<Priority(id={self.id}, name='{self.name}', level={self.level})>"
|
||||
@@ -0,0 +1,21 @@
|
||||
"""Role model."""
|
||||
|
||||
from sqlalchemy import Column, String, Boolean, Text, Integer
|
||||
from sqlalchemy.orm import relationship
|
||||
from request_app.models.base import Base, TimestampMixin
|
||||
|
||||
|
||||
class Role(Base, TimestampMixin):
|
||||
"""Role model."""
|
||||
|
||||
__tablename__ = "roles"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
name = Column(String(100), unique=True, nullable=False)
|
||||
description = Column(Text)
|
||||
is_system = Column(Boolean, default=False)
|
||||
|
||||
user_roles = relationship("UserRole", back_populates="role", cascade="all, delete-orphan")
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"<Role(id={self.id}, name='{self.name}')>"
|
||||
@@ -0,0 +1,20 @@
|
||||
"""System settings model."""
|
||||
|
||||
from sqlalchemy import Column, String, Integer, Text, Boolean
|
||||
from request_app.models.base import Base, TimestampMixin
|
||||
|
||||
|
||||
class SystemSetting(Base, TimestampMixin):
|
||||
"""System settings model for storing configuration."""
|
||||
|
||||
__tablename__ = "system_settings"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
category = Column(String(50), nullable=False, index=True) # email, sms, general
|
||||
key = Column(String(100), nullable=False, unique=True, index=True)
|
||||
value = Column(Text)
|
||||
description = Column(String(500))
|
||||
is_secret = Column(Boolean, default=False) # For passwords/keys
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"<SystemSetting(category='{self.category}', key='{self.key}')>"
|
||||
@@ -0,0 +1,17 @@
|
||||
"""Status model."""
|
||||
|
||||
from sqlalchemy import Column, String, Boolean, Integer
|
||||
from request_app.models.base import Base, TimestampMixin
|
||||
|
||||
|
||||
class Status(Base, TimestampMixin):
|
||||
"""Status model."""
|
||||
|
||||
__tablename__ = "statuses"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
name = Column(String(50), unique=True, nullable=False)
|
||||
is_final = Column(Boolean, default=False) # Can a ticket be closed with this status?
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"<Status(id={self.id}, name='{self.name}', is_final={self.is_final})>"
|
||||
@@ -0,0 +1,39 @@
|
||||
"""Ticket model."""
|
||||
|
||||
from sqlalchemy import Column, String, Text, DateTime, ForeignKey, Integer
|
||||
from sqlalchemy.orm import relationship
|
||||
from request_app.models.base import Base, TimestampMixin
|
||||
|
||||
|
||||
class Ticket(Base, TimestampMixin):
|
||||
"""Ticket model."""
|
||||
|
||||
__tablename__ = "tickets"
|
||||
__table_args__ = {"sqlite_autoincrement": True}
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
subject = Column(String(4000), nullable=False)
|
||||
description = Column(Text)
|
||||
category_id = Column(Integer, ForeignKey("categories.id", ondelete="SET NULL"), nullable=False)
|
||||
priority_id = Column(Integer, ForeignKey("priorities.id", ondelete="SET NULL"), nullable=False)
|
||||
status_id = Column(Integer, ForeignKey("statuses.id", ondelete="SET NULL"), nullable=False)
|
||||
source = Column(String(20), nullable=False) # email, web, phone, sms
|
||||
opened_by = Column(Integer, ForeignKey("users.id", ondelete="SET NULL"), nullable=False)
|
||||
assigned_to_id = Column(Integer, ForeignKey("users.id", ondelete="SET NULL"))
|
||||
company_id = Column(Integer, ForeignKey("companies.id", ondelete="SET NULL"))
|
||||
location_id = Column(Integer, ForeignKey("locations.id", ondelete="SET NULL"))
|
||||
closed_at = Column(DateTime)
|
||||
|
||||
# Relationships
|
||||
user = relationship("User", back_populates="tickets", foreign_keys=[opened_by])
|
||||
assigned_user = relationship("User", back_populates="assigned_tickets", foreign_keys=[assigned_to_id])
|
||||
category = relationship("Category", back_populates="tickets")
|
||||
priority = relationship("Priority")
|
||||
status = relationship("Status")
|
||||
company = relationship("Company", back_populates="tickets")
|
||||
location = relationship("Location", back_populates="tickets")
|
||||
comments = relationship("Comment", back_populates="ticket", cascade="all, delete-orphan")
|
||||
email_messages = relationship("EmailMessage", back_populates="ticket", cascade="all, delete-orphan")
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"<Ticket(id={self.id}, subject='{self.subject}')>"
|
||||
@@ -0,0 +1,25 @@
|
||||
"""Ticket system event model."""
|
||||
|
||||
from sqlalchemy import Column, Integer, String, Text, DateTime, ForeignKey
|
||||
from sqlalchemy.orm import relationship
|
||||
from request_app.models.base import Base, TimestampMixin
|
||||
|
||||
|
||||
class TicketEvent(Base, TimestampMixin):
|
||||
"""System events for a ticket (audit log)."""
|
||||
|
||||
__tablename__ = "ticket_events"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
ticket_id = Column(Integer, ForeignKey("tickets.id", ondelete="CASCADE"), nullable=False, index=True)
|
||||
event_type = Column(String(50), nullable=False) # created, email_sent, comment_added, status_changed, assigned, etc.
|
||||
message = Column(Text, nullable=False)
|
||||
user_id = Column(Integer, ForeignKey("users.id", ondelete="SET NULL"))
|
||||
extra_data = Column(Text) # JSON for additional context
|
||||
|
||||
# Relationships
|
||||
ticket = relationship("Ticket")
|
||||
user = relationship("User")
|
||||
|
||||
def __repr__(self):
|
||||
return f"<TicketEvent(id={self.id}, ticket={self.ticket_id}, type='{self.event_type}')>"
|
||||
@@ -0,0 +1,33 @@
|
||||
"""User model."""
|
||||
|
||||
from sqlalchemy import Column, String, Boolean, Integer
|
||||
from sqlalchemy.orm import relationship
|
||||
from request_app.models.base import Base, TimestampMixin
|
||||
|
||||
|
||||
class User(Base, TimestampMixin):
|
||||
"""Local users table.
|
||||
|
||||
Stores both local users and platform users (synced via JWT).
|
||||
Platform users are auto-created on first access.
|
||||
"""
|
||||
|
||||
__tablename__ = "users"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
email = Column(String(255), unique=True, index=True, nullable=False)
|
||||
first_name = Column(String(100), nullable=False, default="")
|
||||
last_name = Column(String(100), nullable=False, default="")
|
||||
phone = Column(String(50))
|
||||
password_hash = Column(String(255), nullable=True) # Only for local users
|
||||
is_active = Column(Boolean, default=True)
|
||||
source = Column(String(20), default="local") # "local" or "platform"
|
||||
|
||||
# Relationships
|
||||
tickets = relationship("Ticket", back_populates="user", foreign_keys="Ticket.opened_by")
|
||||
assigned_tickets = relationship("Ticket", back_populates="assigned_user", foreign_keys="Ticket.assigned_to_id")
|
||||
comments = relationship("Comment", back_populates="user")
|
||||
user_roles = relationship("UserRole", back_populates="user", cascade="all, delete-orphan")
|
||||
|
||||
def __repr__(self) -> str:
|
||||
return f"<User(id={self.id}, email='{self.email}')>"
|
||||
@@ -0,0 +1,18 @@
|
||||
"""UserRole model."""
|
||||
|
||||
from sqlalchemy import Column, Integer, ForeignKey
|
||||
from sqlalchemy.orm import relationship
|
||||
from request_app.models.base import Base, TimestampMixin
|
||||
|
||||
|
||||
class UserRole(Base, TimestampMixin):
|
||||
"""UserRole model."""
|
||||
|
||||
__tablename__ = "user_roles"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
user_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"), nullable=False)
|
||||
role_id = Column(Integer, ForeignKey("roles.id", ondelete="CASCADE"), nullable=False)
|
||||
|
||||
user = relationship("User", back_populates="user_roles")
|
||||
role = relationship("Role", back_populates="user_roles")
|
||||
@@ -0,0 +1,9 @@
|
||||
"""Repository package."""
|
||||
|
||||
from request_app.repositories.ticket_repository import TicketRepository
|
||||
from request_app.repositories.user_repository import UserRepository
|
||||
|
||||
__all__ = [
|
||||
"TicketRepository",
|
||||
"UserRepository",
|
||||
]
|
||||
@@ -0,0 +1,73 @@
|
||||
"""Base repository."""
|
||||
|
||||
from typing import Type, TypeVar, Optional, List
|
||||
from sqlalchemy.orm import Session
|
||||
from sqlalchemy import select
|
||||
|
||||
T = TypeVar("T")
|
||||
|
||||
|
||||
class BaseRepository:
|
||||
"""Base repository class."""
|
||||
|
||||
def __init__(self, model: Type[T], db: Session):
|
||||
self.model = model
|
||||
self.db = db
|
||||
|
||||
def get_by_id(self, id: int) -> Optional[T]:
|
||||
"""Get entity by ID."""
|
||||
return self.db.query(self.model).filter(self.model.id == id).first()
|
||||
|
||||
def get_all(
|
||||
self,
|
||||
page: int = 1,
|
||||
page_size: int = 10,
|
||||
**filters
|
||||
) -> tuple[List[T], int]:
|
||||
"""Get all entities with pagination and filters."""
|
||||
query = self.db.query(self.model)
|
||||
|
||||
# Apply filters
|
||||
for attr, value in filters.items():
|
||||
if hasattr(self.model, attr) and value is not None:
|
||||
query = query.filter(getattr(self.model, attr) == value)
|
||||
|
||||
# Get total count
|
||||
total = query.count()
|
||||
|
||||
# Get paginated results
|
||||
entities = query.order_by(self.model.id.desc()).offset((page - 1) * page_size).limit(page_size).all()
|
||||
|
||||
return entities, total
|
||||
|
||||
def create(self, **kwargs) -> T:
|
||||
"""Create new entity."""
|
||||
entity = self.model(**kwargs)
|
||||
self.db.add(entity)
|
||||
self.db.commit()
|
||||
self.db.refresh(entity)
|
||||
return entity
|
||||
|
||||
def update(self, id: int, **kwargs) -> Optional[T]:
|
||||
"""Update entity."""
|
||||
entity = self.get_by_id(id)
|
||||
if entity:
|
||||
for key, value in kwargs.items():
|
||||
if hasattr(entity, key):
|
||||
setattr(entity, key, value)
|
||||
self.db.commit()
|
||||
self.db.refresh(entity)
|
||||
return entity
|
||||
|
||||
def delete(self, id: int) -> bool:
|
||||
"""Delete entity."""
|
||||
entity = self.get_by_id(id)
|
||||
if entity:
|
||||
self.db.delete(entity)
|
||||
self.db.commit()
|
||||
return True
|
||||
return False
|
||||
|
||||
def exists(self, id: int) -> bool:
|
||||
"""Check if entity exists."""
|
||||
return self.db.query(self.model).filter(self.model.id == id).first() is not None
|
||||
@@ -0,0 +1,72 @@
|
||||
"""Ticket repository."""
|
||||
|
||||
from typing import List, Optional, Tuple
|
||||
from sqlalchemy.orm import Session
|
||||
from sqlalchemy import func, and_, or_
|
||||
from request_app.models.ticket import Ticket
|
||||
from request_app.repositories.base_repository import BaseRepository
|
||||
|
||||
|
||||
class TicketRepository(BaseRepository):
|
||||
"""Ticket repository."""
|
||||
|
||||
def __init__(self, db: Session):
|
||||
super().__init__(Ticket, db)
|
||||
|
||||
def get_tickets_with_joins(
|
||||
self,
|
||||
page: int = 1,
|
||||
page_size: int = 10,
|
||||
status_id: Optional[int] = None,
|
||||
priority_id: Optional[int] = None,
|
||||
assigned_to_id: Optional[int] = None,
|
||||
search: Optional[str] = None
|
||||
) -> Tuple[List[Ticket], int]:
|
||||
"""Get tickets with joins for efficient querying."""
|
||||
query = self.db.query(Ticket)
|
||||
|
||||
# Apply 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(
|
||||
or_(
|
||||
Ticket.subject.ilike(search_term),
|
||||
Ticket.description.ilike(search_term)
|
||||
)
|
||||
)
|
||||
|
||||
# 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 get_tickets_by_user(self, user_id: int) -> List[Ticket]:
|
||||
"""Get tickets created by user."""
|
||||
return self.db.query(Ticket).filter(Ticket.opened_by == user_id).order_by(Ticket.created_at.desc()).all()
|
||||
|
||||
def get_tickets_assigned_to(self, user_id: int) -> List[Ticket]:
|
||||
"""Get tickets assigned to user."""
|
||||
return self.db.query(Ticket).filter(Ticket.assigned_to_id == user_id).order_by(Ticket.created_at.desc()).all()
|
||||
|
||||
def get_active_tickets_count(self) -> int:
|
||||
"""Get count of active tickets."""
|
||||
return self.db.query(func.count(Ticket.id)).filter(Ticket.status_id != 4).scalar()
|
||||
|
||||
def get_tickets_by_status(self, status_id: int) -> List[Ticket]:
|
||||
"""Get tickets by status."""
|
||||
return self.db.query(Ticket).filter(Ticket.status_id == status_id).order_by(Ticket.created_at.desc()).all()
|
||||
|
||||
def get_tickets_by_priority(self, priority_id: int) -> List[Ticket]:
|
||||
"""Get tickets by priority."""
|
||||
return self.db.query(Ticket).filter(Ticket.priority_id == priority_id).order_by(Ticket.created_at.desc()).all()
|
||||
@@ -0,0 +1,33 @@
|
||||
"""User repository."""
|
||||
|
||||
from typing import List, Optional
|
||||
from sqlalchemy.orm import Session
|
||||
from sqlalchemy import or_
|
||||
from request_app.models.user import User
|
||||
from request_app.repositories.base_repository import BaseRepository
|
||||
|
||||
|
||||
class UserRepository(BaseRepository):
|
||||
"""User repository."""
|
||||
|
||||
def __init__(self, db: Session):
|
||||
super().__init__(User, db)
|
||||
|
||||
def get_user_by_email(self, email: str) -> Optional[User]:
|
||||
"""Get user by email."""
|
||||
return self.db.query(User).filter(User.email == email).first()
|
||||
|
||||
def get_active_users(self) -> List[User]:
|
||||
"""Get active users."""
|
||||
return self.db.query(User).filter(User.is_active == True).order_by(User.created_at.desc()).all()
|
||||
|
||||
def search_users(self, search_term: str) -> List[User]:
|
||||
"""Search users by name or email."""
|
||||
search_term = f"%{search_term}%"
|
||||
return self.db.query(User).filter(
|
||||
or_(
|
||||
User.first_name.ilike(search_term),
|
||||
User.last_name.ilike(search_term),
|
||||
User.email.ilike(search_term)
|
||||
)
|
||||
).all()
|
||||
@@ -0,0 +1,35 @@
|
||||
"""Schemas package."""
|
||||
|
||||
from request_app.schemas.ticket import (
|
||||
TicketCreate,
|
||||
TicketUpdate,
|
||||
TicketResponse,
|
||||
TicketListResponse,
|
||||
)
|
||||
from request_app.schemas.user import (
|
||||
UserCreate,
|
||||
UserUpdate,
|
||||
UserResponse,
|
||||
UserListResponse,
|
||||
)
|
||||
from request_app.schemas.auth import (
|
||||
TokenResponse,
|
||||
TokenRequest,
|
||||
UserRegisterRequest,
|
||||
)
|
||||
from request_app.schemas.common import PaginationParams
|
||||
|
||||
__all__ = [
|
||||
"TicketCreate",
|
||||
"TicketUpdate",
|
||||
"TicketResponse",
|
||||
"TicketListResponse",
|
||||
"UserCreate",
|
||||
"UserUpdate",
|
||||
"UserResponse",
|
||||
"UserListResponse",
|
||||
"TokenResponse",
|
||||
"TokenRequest",
|
||||
"UserRegisterRequest",
|
||||
"PaginationParams",
|
||||
]
|
||||
@@ -0,0 +1,32 @@
|
||||
"""Auth schemas."""
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
from typing import Optional
|
||||
from datetime import datetime
|
||||
|
||||
|
||||
class TokenRequest(BaseModel):
|
||||
"""Token request schema."""
|
||||
|
||||
email: str
|
||||
password: str
|
||||
|
||||
|
||||
class TokenResponse(BaseModel):
|
||||
"""Token response schema."""
|
||||
|
||||
access_token: str
|
||||
token_type: str = "bearer"
|
||||
expires_in: int
|
||||
user: dict
|
||||
|
||||
|
||||
class UserRegisterRequest(BaseModel):
|
||||
"""User registration request schema."""
|
||||
|
||||
email: str
|
||||
password: str = Field(..., min_length=6)
|
||||
first_name: str = Field(..., min_length=1, max_length=100)
|
||||
last_name: str = Field(..., min_length=1, max_length=100)
|
||||
phone: Optional[str] = None
|
||||
role_id: Optional[int] = None
|
||||
@@ -0,0 +1,59 @@
|
||||
"""Common schemas."""
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
from typing import Optional, Any
|
||||
|
||||
|
||||
class PaginationParams(BaseModel):
|
||||
"""Pagination parameters."""
|
||||
|
||||
page: int = Field(1, ge=1, description="Page number")
|
||||
page_size: int = Field(10, ge=1, le=100, description="Items per page")
|
||||
|
||||
@property
|
||||
def offset(self) -> int:
|
||||
"""Calculate offset for pagination."""
|
||||
return (self.page - 1) * self.page_size
|
||||
|
||||
|
||||
class MessageResponse(BaseModel):
|
||||
"""Generic success message response."""
|
||||
|
||||
message: str
|
||||
success: bool = True
|
||||
|
||||
|
||||
class ErrorResponse(BaseModel):
|
||||
"""Generic error response."""
|
||||
|
||||
message: str
|
||||
error_code: Optional[str] = None
|
||||
success: bool = False
|
||||
|
||||
|
||||
class PaginatedResponse(BaseModel):
|
||||
"""Generic paginated response."""
|
||||
|
||||
items: list[Any]
|
||||
total: int
|
||||
page: int
|
||||
page_size: int
|
||||
total_pages: int
|
||||
|
||||
@classmethod
|
||||
def create(
|
||||
cls,
|
||||
items: list[Any],
|
||||
total: int,
|
||||
page: int,
|
||||
page_size: int
|
||||
) -> "PaginatedResponse":
|
||||
"""Create paginated response."""
|
||||
total_pages = (total + page_size - 1) // page_size
|
||||
return cls(
|
||||
items=items,
|
||||
total=total,
|
||||
page=page,
|
||||
page_size=page_size,
|
||||
total_pages=total_pages
|
||||
)
|
||||
@@ -0,0 +1,64 @@
|
||||
"""Email message schemas."""
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
from typing import Optional, List
|
||||
from datetime import datetime
|
||||
|
||||
|
||||
class EmailAttachmentResponse(BaseModel):
|
||||
"""Email attachment response schema."""
|
||||
id: int
|
||||
filename: str
|
||||
content_type: Optional[str]
|
||||
file_size: Optional[int]
|
||||
created_at: datetime
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
|
||||
class EmailMessageResponse(BaseModel):
|
||||
"""Email message response schema."""
|
||||
id: int
|
||||
ticket_id: int
|
||||
direction: str
|
||||
message_id: Optional[str]
|
||||
in_reply_to: Optional[str]
|
||||
from_address: str
|
||||
to_addresses: str
|
||||
cc_addresses: Optional[str]
|
||||
subject: Optional[str]
|
||||
body_text: Optional[str]
|
||||
body_html: Optional[str]
|
||||
is_read: bool
|
||||
sent_at: Optional[datetime]
|
||||
received_at: Optional[datetime]
|
||||
sent_by: Optional[int]
|
||||
created_at: datetime
|
||||
attachments: List[EmailAttachmentResponse] = []
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
|
||||
class EmailMessageListResponse(BaseModel):
|
||||
"""Email message list response schema."""
|
||||
messages: List[EmailMessageResponse]
|
||||
total: int
|
||||
|
||||
|
||||
class SendEmailRequest(BaseModel):
|
||||
"""Send email request schema."""
|
||||
to_addresses: str = Field(..., description="Recipient email addresses (comma-separated)")
|
||||
cc_addresses: Optional[str] = Field(None, description="CC email addresses (comma-separated)")
|
||||
subject: str = Field(..., min_length=1, max_length=4000)
|
||||
body_text: Optional[str] = None
|
||||
body_html: Optional[str] = None
|
||||
in_reply_to: Optional[str] = Field(None, description="Message-ID being replied to")
|
||||
|
||||
|
||||
class ForwardEmailRequest(BaseModel):
|
||||
"""Forward email request schema."""
|
||||
to_addresses: str = Field(..., description="Recipient email addresses (comma-separated)")
|
||||
cc_addresses: Optional[str] = Field(None, description="CC email addresses (comma-separated)")
|
||||
add_message: Optional[str] = Field(None, description="Additional message to prepend")
|
||||
@@ -0,0 +1,179 @@
|
||||
"""Reference data schemas."""
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
from typing import Optional, List
|
||||
from datetime import datetime
|
||||
|
||||
|
||||
class RoleBase(BaseModel):
|
||||
"""Role base schema."""
|
||||
name: str = Field(..., min_length=1, max_length=50)
|
||||
description: Optional[str] = None
|
||||
|
||||
|
||||
class RoleCreate(RoleBase):
|
||||
"""Role creation schema."""
|
||||
pass
|
||||
|
||||
|
||||
class RoleResponse(RoleBase):
|
||||
"""Role response schema."""
|
||||
id: int
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
|
||||
class StatusBase(BaseModel):
|
||||
"""Status base schema."""
|
||||
name: str = Field(..., min_length=1, max_length=50)
|
||||
is_final: bool = False
|
||||
|
||||
|
||||
class StatusCreate(StatusBase):
|
||||
"""Status creation schema."""
|
||||
pass
|
||||
|
||||
|
||||
class StatusResponse(StatusBase):
|
||||
"""Status response schema."""
|
||||
id: int
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
|
||||
class PriorityBase(BaseModel):
|
||||
"""Priority base schema."""
|
||||
name: str = Field(..., min_length=1, max_length=50)
|
||||
level: int = Field(..., ge=1, le=10)
|
||||
default_response_time_minutes: int = Field(60, ge=1)
|
||||
|
||||
|
||||
class PriorityCreate(PriorityBase):
|
||||
"""Priority creation schema."""
|
||||
pass
|
||||
|
||||
|
||||
class PriorityResponse(PriorityBase):
|
||||
"""Priority response schema."""
|
||||
id: int
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
|
||||
class CategoryBase(BaseModel):
|
||||
"""Category base schema."""
|
||||
name: str = Field(..., min_length=1, max_length=100)
|
||||
parent_id: Optional[int] = None
|
||||
|
||||
|
||||
class CategoryCreate(CategoryBase):
|
||||
"""Category creation schema."""
|
||||
pass
|
||||
|
||||
|
||||
class CategoryResponse(CategoryBase):
|
||||
"""Category response schema."""
|
||||
id: int
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
|
||||
class CompanyBase(BaseModel):
|
||||
"""Company base schema."""
|
||||
name: str = Field(..., min_length=1, max_length=255)
|
||||
address: Optional[str] = None
|
||||
phone: Optional[str] = None
|
||||
website: Optional[str] = None
|
||||
|
||||
|
||||
class CompanyCreate(CompanyBase):
|
||||
"""Company creation schema."""
|
||||
pass
|
||||
|
||||
|
||||
class CompanyResponse(CompanyBase):
|
||||
"""Company response schema."""
|
||||
id: int
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
|
||||
class LocationBase(BaseModel):
|
||||
"""Location base schema."""
|
||||
name: str = Field(..., min_length=1, max_length=255)
|
||||
address: Optional[str] = None
|
||||
phone: Optional[str] = None
|
||||
|
||||
|
||||
class LocationCreate(LocationBase):
|
||||
"""Location creation schema."""
|
||||
pass
|
||||
|
||||
|
||||
class LocationResponse(LocationBase):
|
||||
"""Location response schema."""
|
||||
id: int
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
|
||||
class DepartmentBase(BaseModel):
|
||||
"""Department base schema."""
|
||||
name: str = Field(..., min_length=1, max_length=255)
|
||||
|
||||
|
||||
class DepartmentCreate(DepartmentBase):
|
||||
"""Department creation schema."""
|
||||
pass
|
||||
|
||||
|
||||
class DepartmentResponse(DepartmentBase):
|
||||
"""Department response schema."""
|
||||
id: int
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
|
||||
class NotificationResponse(BaseModel):
|
||||
"""Notification response schema."""
|
||||
id: int
|
||||
user_id: int
|
||||
ticket_id: Optional[int]
|
||||
type: str
|
||||
title: str
|
||||
message: str
|
||||
is_read: int
|
||||
is_delivered: int
|
||||
sent_at: Optional[datetime]
|
||||
created_at: datetime
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
|
||||
class NotificationListResponse(BaseModel):
|
||||
"""Notification list response schema."""
|
||||
notifications: List[NotificationResponse]
|
||||
total: int
|
||||
unread_count: int
|
||||
@@ -0,0 +1,50 @@
|
||||
"""Settings schemas."""
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
from typing import Optional, List
|
||||
from datetime import datetime
|
||||
|
||||
|
||||
class SettingResponse(BaseModel):
|
||||
"""Setting response schema."""
|
||||
id: int
|
||||
category: str
|
||||
key: str
|
||||
value: Optional[str]
|
||||
description: Optional[str]
|
||||
is_secret: bool
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
|
||||
class SettingUpdate(BaseModel):
|
||||
"""Setting update schema."""
|
||||
value: str = Field(..., min_length=1)
|
||||
|
||||
|
||||
class SettingListResponse(BaseModel):
|
||||
"""Settings list response by category."""
|
||||
category: str
|
||||
settings: List[SettingResponse]
|
||||
|
||||
|
||||
class EmailSettings(BaseModel):
|
||||
"""Email settings schema."""
|
||||
smtp_server: str
|
||||
smtp_port: int
|
||||
smtp_username: str
|
||||
smtp_password: str
|
||||
email_from: str
|
||||
imap_server: Optional[str] = None
|
||||
imap_port: Optional[int] = None
|
||||
use_tls: bool = True
|
||||
email_fetch_interval: Optional[int] = 300
|
||||
email_delete_after_fetch: Optional[bool] = False
|
||||
|
||||
|
||||
class SMSSettings(BaseModel):
|
||||
"""SMS settings schema."""
|
||||
twilio_account_sid: str
|
||||
twilio_auth_token: str
|
||||
twilio_from_number: str
|
||||
@@ -0,0 +1,78 @@
|
||||
"""Ticket schemas."""
|
||||
|
||||
from pydantic import BaseModel, Field
|
||||
from typing import Optional, List
|
||||
from datetime import datetime
|
||||
|
||||
|
||||
class TicketCreate(BaseModel):
|
||||
"""Ticket creation schema."""
|
||||
|
||||
subject: str = Field(..., min_length=1, max_length=4000)
|
||||
description: Optional[str] = None
|
||||
category_id: int = Field(..., description="Category ID")
|
||||
priority_id: int = Field(..., description="Priority ID")
|
||||
status_id: int = Field(..., description="Status ID")
|
||||
assigned_to_id: Optional[int] = None
|
||||
source: str = Field(default="web")
|
||||
|
||||
|
||||
class TicketUpdate(BaseModel):
|
||||
"""Ticket update schema."""
|
||||
|
||||
subject: Optional[str] = Field(None, min_length=1, max_length=4000)
|
||||
description: Optional[str] = None
|
||||
category_id: Optional[int] = None
|
||||
priority_id: Optional[int] = None
|
||||
status_id: Optional[int] = None
|
||||
assigned_to_id: Optional[int] = None
|
||||
closed_at: Optional[datetime] = None
|
||||
|
||||
|
||||
class CommentCreate(BaseModel):
|
||||
"""Comment creation schema."""
|
||||
|
||||
comment_text: str = Field(..., min_length=1)
|
||||
|
||||
|
||||
class CommentResponse(BaseModel):
|
||||
"""Comment response schema."""
|
||||
|
||||
id: int
|
||||
ticket_id: int
|
||||
created_by: int
|
||||
comment_text: str
|
||||
created_at: datetime
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
|
||||
class TicketResponse(BaseModel):
|
||||
"""Ticket response schema."""
|
||||
|
||||
id: int
|
||||
subject: str
|
||||
description: Optional[str]
|
||||
category_id: int
|
||||
priority_id: int
|
||||
status_id: int
|
||||
source: str
|
||||
opened_by: int
|
||||
assigned_to_id: Optional[int]
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
closed_at: Optional[datetime]
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
|
||||
class TicketListResponse(BaseModel):
|
||||
"""Ticket list response schema."""
|
||||
|
||||
tickets: List[TicketResponse]
|
||||
total: int
|
||||
page: int
|
||||
page_size: int
|
||||
total_pages: int
|
||||
@@ -0,0 +1,61 @@
|
||||
"""User schemas."""
|
||||
|
||||
from pydantic import BaseModel, EmailStr, Field
|
||||
from typing import Optional
|
||||
from datetime import datetime
|
||||
from request_app.schemas.common import PaginationParams
|
||||
|
||||
|
||||
class UserCreate(BaseModel):
|
||||
"""User creation schema."""
|
||||
|
||||
email: EmailStr
|
||||
password: str = Field(..., min_length=6)
|
||||
first_name: str = Field(..., min_length=1, max_length=100)
|
||||
last_name: str = Field(..., min_length=1, max_length=100)
|
||||
phone: Optional[str] = None
|
||||
role_id: Optional[int] = None
|
||||
|
||||
|
||||
class UserUpdate(BaseModel):
|
||||
"""User update schema."""
|
||||
|
||||
first_name: Optional[str] = Field(None, min_length=1, max_length=100)
|
||||
last_name: Optional[str] = Field(None, min_length=1, max_length=100)
|
||||
email: Optional[str] = None
|
||||
phone: Optional[str] = None
|
||||
is_active: Optional[bool] = None
|
||||
|
||||
|
||||
class UserResponse(BaseModel):
|
||||
"""User response schema."""
|
||||
|
||||
id: int
|
||||
first_name: str
|
||||
last_name: str
|
||||
email: str
|
||||
phone: Optional[str]
|
||||
is_active: bool
|
||||
created_at: datetime
|
||||
updated_at: datetime
|
||||
roles: list[str] = []
|
||||
departments: list[str] = []
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
|
||||
class UserListResponse(BaseModel):
|
||||
"""User list response schema."""
|
||||
|
||||
users: list[UserResponse]
|
||||
total: int
|
||||
page: int
|
||||
page_size: int
|
||||
total_pages: int
|
||||
|
||||
|
||||
class UserWithRoles(UserResponse):
|
||||
"""User with roles response schema."""
|
||||
|
||||
role_ids: list[int] = []
|
||||
@@ -0,0 +1,11 @@
|
||||
"""Services package."""
|
||||
|
||||
from request_app.services.user_service import UserService
|
||||
from request_app.services.ticket_service import TicketService
|
||||
from request_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 request_app.models.email_message import EmailMessage, EmailAttachment
|
||||
from request_app.models.ticket import Ticket
|
||||
from request_app.core.exceptions import NotFoundException
|
||||
from request_app.integrations.email import EmailClient
|
||||
from request_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 request_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 request_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 request_app.models.email_outbox import EmailOutbox
|
||||
from request_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 request_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 request_app.models.ticket import Ticket
|
||||
from request_app.models.user import User
|
||||
from request_app.models.email_message import EmailMessage
|
||||
from request_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 request_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 request_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 request_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 request_app.models.notification import Notification
|
||||
from request_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 request_app.models.notification_template import NotificationTemplate, SavedFilter
|
||||
from request_app.models.notification import Notification
|
||||
from request_app.models.user import User
|
||||
from request_app.models.ticket import Ticket
|
||||
from request_app.integrations.email import EmailClient
|
||||
from request_app.integrations.sms import SMSClient
|
||||
from request_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 request_app.services.email_outbox_service import EmailOutboxService
|
||||
from request_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 request_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 request_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 request_app.models.status import Status
|
||||
from request_app.models.priority import Priority
|
||||
from request_app.models.category import Category
|
||||
from request_app.models.extra import Company, Location, Department
|
||||
from request_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 request_app.models.setting import SystemSetting
|
||||
from request_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 request_app.models.ticket_event import TicketEvent
|
||||
from request_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 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)
|
||||
@@ -0,0 +1,88 @@
|
||||
"""User service - platform integration."""
|
||||
|
||||
from typing import List, Optional, Tuple
|
||||
from sqlalchemy.orm import Session
|
||||
from datetime import datetime
|
||||
|
||||
from request_app.models.user import User
|
||||
from request_app.models.extra import UserDepartment
|
||||
from request_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
|
||||
@@ -0,0 +1,65 @@
|
||||
"""Pydantic settings configuration."""
|
||||
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
from typing import List
|
||||
from functools import lru_cache
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
"""Application settings."""
|
||||
|
||||
model_config = SettingsConfigDict(
|
||||
env_file=".env",
|
||||
env_file_encoding="utf-8",
|
||||
case_sensitive=True
|
||||
)
|
||||
|
||||
# Application
|
||||
APP_ENV: str = "development"
|
||||
APP_DEBUG: bool = True
|
||||
APP_NAME: str = "Service Request System"
|
||||
APP_VERSION: str = "1.0.0"
|
||||
APP_CORS_ORIGINS: str = "http://localhost:3000"
|
||||
|
||||
# Database
|
||||
DATABASE_URL: str = "sqlite:///./service_request.db"
|
||||
|
||||
# Redis
|
||||
REDIS_URL: str = "redis://localhost:6379/0"
|
||||
|
||||
# RabbitMQ
|
||||
RABBITMQ_URL: str = "amqp://guest:guest@localhost:5672/"
|
||||
|
||||
# JWT
|
||||
JWT_SECRET_KEY: str = "dev-secret-key-here-change-in-production"
|
||||
JWT_ALGORITHM: str = "HS256"
|
||||
JWT_ACCESS_TOKEN_EXPIRE_MINUTES: int = 30
|
||||
|
||||
# Email
|
||||
SMTP_SERVER: str = "smtp.gmail.com"
|
||||
SMTP_PORT: int = 465
|
||||
SMTP_USERNAME: str = ""
|
||||
SMTP_PASSWORD: str = ""
|
||||
EMAIL_FROM: str = ""
|
||||
IMAP_SERVER: str = "imap.gmail.com"
|
||||
IMAP_PORT: int = 993
|
||||
|
||||
# SMS
|
||||
TWILIO_ACCOUNT_SID: str = ""
|
||||
TWILIO_AUTH_TOKEN: str = ""
|
||||
TWILIO_FROM_NUMBER: str = ""
|
||||
|
||||
# Migration
|
||||
MANAGEENGINE_CONNECTION_STRING: str = ""
|
||||
|
||||
# Platform integration
|
||||
PLATFORM_API_URL: str = "http://platform:8000"
|
||||
PLATFORM_API_KEY: str = ""
|
||||
PLATFORM_JWT_PUBLIC_KEY: str = ""
|
||||
PLATFORM_JWT_ALGORITHM: str = "RS256"
|
||||
|
||||
|
||||
@lru_cache()
|
||||
def get_settings() -> Settings:
|
||||
"""Get cached settings instance."""
|
||||
return Settings()
|
||||
@@ -0,0 +1 @@
|
||||
"""Celery workers package."""
|
||||
@@ -0,0 +1,35 @@
|
||||
"""Shared Celery application configuration."""
|
||||
|
||||
from celery import Celery
|
||||
from request_app.settings import get_settings
|
||||
|
||||
settings = get_settings()
|
||||
|
||||
celery_app = Celery(
|
||||
"service_request_workers",
|
||||
broker=settings.RABBITMQ_URL,
|
||||
backend=settings.REDIS_URL
|
||||
)
|
||||
|
||||
celery_app.conf.update(
|
||||
task_serializer="json",
|
||||
accept_content=["json"],
|
||||
result_serializer="json",
|
||||
timezone="UTC",
|
||||
enable_utc=True,
|
||||
task_track_started=True,
|
||||
task_time_limit=30 * 60,
|
||||
task_soft_time_limit=25 * 60,
|
||||
task_routes={
|
||||
"app.workers.email_worker.*": {"queue": "email"},
|
||||
"app.workers.sms_worker.*": {"queue": "sms"},
|
||||
},
|
||||
beat_schedule={
|
||||
"fetch-incoming-emails": {
|
||||
"task": "app.workers.email_worker.fetch_incoming_emails",
|
||||
"schedule": 60.0, # check every minute; actual interval controlled by email_fetch_interval setting
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
celery_app.autodiscover_tasks(["app.workers"])
|
||||
@@ -0,0 +1,310 @@
|
||||
"""Email worker for Celery."""
|
||||
|
||||
import re
|
||||
from request_app.workers.celery_app import celery_app
|
||||
from request_app.core.database import SessionLocal
|
||||
from request_app.integrations.email import EmailClient
|
||||
from request_app.models.ticket import Ticket
|
||||
from request_app.settings import get_settings
|
||||
from request_app.core.logging import logger
|
||||
|
||||
settings = get_settings()
|
||||
|
||||
# Match ticket ID in various formats:
|
||||
# "Заявка #123", "Re: Заявка #123 - ..."
|
||||
# "Re: тест №44"
|
||||
# "[#44] тест", "57 [#57] барабулька"
|
||||
TICKET_SUBJECT_RE = re.compile(
|
||||
r"(?:Заявка\s*#|#\[?|№\s*?)(\d+)",
|
||||
re.IGNORECASE
|
||||
)
|
||||
|
||||
|
||||
@celery_app.task(bind=True, max_retries=3)
|
||||
def process_email_task(
|
||||
self,
|
||||
ticket_id: int,
|
||||
subject: str,
|
||||
body: str,
|
||||
recipient: str
|
||||
):
|
||||
"""Process email task for ticket notification."""
|
||||
try:
|
||||
db = SessionLocal()
|
||||
|
||||
try:
|
||||
ticket = db.query(Ticket).filter(Ticket.id == ticket_id).first()
|
||||
if not ticket:
|
||||
raise ValueError(f"Ticket {ticket_id} not found")
|
||||
|
||||
email_client = EmailClient(db_session=db)
|
||||
|
||||
result = email_client.send_email(
|
||||
to=recipient,
|
||||
subject=subject,
|
||||
body=body
|
||||
)
|
||||
|
||||
if result["status"] == "error":
|
||||
raise Exception(result["error"])
|
||||
|
||||
return {"status": "success", "ticket_id": ticket_id, "message": "Email sent"}
|
||||
|
||||
except Exception as e:
|
||||
raise self.retry(exc=e, countdown=2 ** self.request.retries)
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
except Exception as e:
|
||||
return {
|
||||
"status": "error",
|
||||
"error": str(e),
|
||||
"task_id": self.request.id
|
||||
}
|
||||
|
||||
|
||||
@celery_app.task
|
||||
def send_ticket_created_notification(
|
||||
ticket_id: int,
|
||||
recipient: str
|
||||
):
|
||||
"""Send notification about ticket creation."""
|
||||
db = SessionLocal()
|
||||
|
||||
try:
|
||||
ticket = db.query(Ticket).filter(Ticket.id == ticket_id).first()
|
||||
if not ticket:
|
||||
return {"status": "error", "message": "Ticket not found"}
|
||||
|
||||
from request_app.models.user import User
|
||||
user = db.query(User).filter(User.id == ticket.opened_by).first()
|
||||
if not user:
|
||||
return {"status": "error", "message": "User not found"}
|
||||
|
||||
subject = f"Тикет #{ticket_id}: {ticket.subject}"
|
||||
body = f"""
|
||||
Тикет #{ticket_id} успешно создан.
|
||||
|
||||
Subject: {ticket.subject}
|
||||
Description: {ticket.description or 'No description'}
|
||||
Priority: {ticket.priority.name}
|
||||
Status: {ticket.status.name}
|
||||
Category: {ticket.category.name}
|
||||
Created: {ticket.created_at}
|
||||
|
||||
Детали: http://localhost:8000/tickets/{ticket_id}
|
||||
""".strip()
|
||||
|
||||
process_email_task.delay(ticket_id, subject, body, recipient)
|
||||
|
||||
return {"status": "success", "ticket_id": ticket_id}
|
||||
|
||||
except Exception as e:
|
||||
return {"status": "error", "error": str(e)}
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
@celery_app.task
|
||||
def send_ticket_assigned_notification(
|
||||
ticket_id: int,
|
||||
recipient: str
|
||||
):
|
||||
"""Send notification about ticket assignment."""
|
||||
db = SessionLocal()
|
||||
|
||||
try:
|
||||
ticket = db.query(Ticket).filter(Ticket.id == ticket_id).first()
|
||||
if not ticket:
|
||||
return {"status": "error", "message": "Ticket not found"}
|
||||
|
||||
from request_app.models.user import User
|
||||
user = db.query(User).filter(User.id == ticket.assigned_to_id).first()
|
||||
if not user:
|
||||
return {"status": "error", "message": "Assigned user not found"}
|
||||
|
||||
subject = f"Назначен тикет #{ticket_id}"
|
||||
body = f"""
|
||||
Вам назначен новый тикет: #{ticket_id}
|
||||
|
||||
Subject: {ticket.subject}
|
||||
Description: {ticket.description or 'No description'}
|
||||
Priority: {ticket.priority.name}
|
||||
Status: {ticket.status.name}
|
||||
|
||||
Информация о тикете: http://localhost:8000/tickets/{ticket_id}
|
||||
""".strip()
|
||||
|
||||
process_email_task.delay(ticket_id, subject, body, recipient)
|
||||
|
||||
return {"status": "success", "ticket_id": ticket_id}
|
||||
|
||||
except Exception as e:
|
||||
return {"status": "error", "error": str(e)}
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
@celery_app.task
|
||||
def fetch_incoming_emails(force: bool = False):
|
||||
"""Fetch emails from IMAP and create tickets or attach to existing ones."""
|
||||
db = SessionLocal()
|
||||
try:
|
||||
from request_app.services.settings_service import SettingsService
|
||||
settings_service = SettingsService(db)
|
||||
|
||||
# Check interval - skip if not enough time has passed (unless forced)
|
||||
import time
|
||||
interval = int(settings_service.get_setting_value('email_fetch_interval', '300'))
|
||||
last_fetch = settings_service.get_setting_value('last_email_fetch', '0')
|
||||
now = time.time()
|
||||
|
||||
if not force and now - float(last_fetch) < interval:
|
||||
return {"status": "skipped", "fetched": 0, "created": 0, "attached": 0}
|
||||
|
||||
# Update last fetch time
|
||||
settings_service.update_setting('last_email_fetch', str(now))
|
||||
|
||||
# Read delete setting
|
||||
delete_after = settings_service.get_setting_value('email_delete_after_fetch', 'false') == 'true'
|
||||
|
||||
email_client = EmailClient(db_session=db)
|
||||
emails = email_client.fetch_emails(folder="INBOX", mark_seen=True, delete_after=delete_after)
|
||||
|
||||
if not emails:
|
||||
return {"status": "success", "fetched": 0, "created": 0, "attached": 0}
|
||||
|
||||
from request_app.services.email_message_service import EmailMessageService
|
||||
from request_app.services.ticket_service import TicketService
|
||||
from request_app.models.user import User
|
||||
from request_app.models.status import Status
|
||||
from request_app.models.priority import Priority
|
||||
from request_app.models.category import Category
|
||||
|
||||
email_service = EmailMessageService(db)
|
||||
ticket_service = TicketService(db)
|
||||
|
||||
created = 0
|
||||
attached = 0
|
||||
|
||||
def parse_from_address(raw: str) -> tuple:
|
||||
"""Parse 'Name <email>' into (name, email)."""
|
||||
import re
|
||||
raw = raw.strip()
|
||||
match = re.match(r'^"?([^"<]*)"?\s*<([^>]+)>$', raw)
|
||||
if match:
|
||||
name = match.group(1).strip()
|
||||
email = match.group(2).strip().lower()
|
||||
return name, email
|
||||
# Just an email address
|
||||
email_match = re.search(r'[\w.+-]+@[\w.-]+\.\w+', raw)
|
||||
if email_match:
|
||||
return "", email_match.group(0).lower()
|
||||
return "", raw.lower()
|
||||
|
||||
for em in emails:
|
||||
subject = em["subject"] or ""
|
||||
from_raw = em["from"] or ""
|
||||
from_name, from_addr = parse_from_address(from_raw)
|
||||
body_text = em["body_text"] or ""
|
||||
body_html = em["body_html"] or ""
|
||||
message_id = em["message_id"] or ""
|
||||
in_reply_to = em["in_reply_to"] or ""
|
||||
date = em["date"]
|
||||
|
||||
# Try to find ticket ID in subject
|
||||
match = TICKET_SUBJECT_RE.search(subject)
|
||||
if match:
|
||||
ticket_id = int(match.group(1))
|
||||
ticket = db.query(Ticket).filter(Ticket.id == ticket_id).first()
|
||||
if ticket:
|
||||
email_service.create_incoming_email(
|
||||
ticket_id=ticket_id,
|
||||
from_address=from_addr,
|
||||
to_addresses=email_client.from_email,
|
||||
subject=subject,
|
||||
body_text=body_text,
|
||||
body_html=body_html,
|
||||
message_id=message_id,
|
||||
in_reply_to=in_reply_to,
|
||||
received_at=date
|
||||
)
|
||||
attached += 1
|
||||
continue
|
||||
|
||||
# No existing ticket found — create new one
|
||||
# Find or create requester (local cache only)
|
||||
requester = db.query(User).filter(User.email == from_addr).first()
|
||||
if not requester and from_addr:
|
||||
# Auto-create user cache entry from email sender
|
||||
if from_name:
|
||||
name_parts = from_name.split(None, 1)
|
||||
first_name = name_parts[0][:100]
|
||||
last_name = name_parts[1][:100] if len(name_parts) > 1 else ""
|
||||
else:
|
||||
first_name = from_addr.split("@")[0].replace(".", " ").replace("_", " ").replace("-", " ").title()
|
||||
last_name = ""
|
||||
requester = User(
|
||||
first_name=first_name,
|
||||
last_name=last_name,
|
||||
email=from_addr,
|
||||
is_active=True
|
||||
)
|
||||
db.add(requester)
|
||||
db.flush()
|
||||
logger.info(f"Auto-created user cache from email: [{requester.id}] {from_addr}")
|
||||
if not requester:
|
||||
requester = db.query(User).filter(User.email == "admin@test.com").first()
|
||||
|
||||
open_status = db.query(Status).filter(Status.name == "Открыто").first()
|
||||
if not open_status:
|
||||
open_status = db.query(Status).first()
|
||||
|
||||
normal_priority = db.query(Priority).filter(Priority.name == "Нормальный").first()
|
||||
if not normal_priority:
|
||||
normal_priority = db.query(Priority).first()
|
||||
|
||||
general_category = db.query(Category).filter(Category.name == "Запрос обслуживания").first()
|
||||
if not general_category:
|
||||
general_category = db.query(Category).first()
|
||||
|
||||
if not (requester and open_status and normal_priority and general_category):
|
||||
logger.warning(f"Skipping email - missing data: requester={requester is not None} status={open_status is not None} priority={normal_priority is not None} category={general_category is not None}")
|
||||
continue
|
||||
|
||||
try:
|
||||
from request_app.schemas.ticket import TicketCreate
|
||||
ticket_data = TicketCreate(
|
||||
subject=subject[:4000],
|
||||
description=body_text or body_html or "",
|
||||
category_id=general_category.id,
|
||||
priority_id=normal_priority.id,
|
||||
status_id=open_status.id,
|
||||
source="email"
|
||||
)
|
||||
ticket = ticket_service.create_ticket(ticket_data, requester.id)
|
||||
logger.info(f"Created ticket [{ticket.id}] from email: '{subject[:50]}' by {from_addr}")
|
||||
|
||||
# Attach the email to the new ticket
|
||||
email_service.create_incoming_email(
|
||||
ticket_id=ticket.id,
|
||||
from_address=from_addr,
|
||||
to_addresses=email_client.from_email,
|
||||
subject=subject,
|
||||
body_text=body_text,
|
||||
body_html=body_html,
|
||||
message_id=message_id,
|
||||
in_reply_to=in_reply_to,
|
||||
received_at=date
|
||||
)
|
||||
created += 1
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to create ticket from email '{subject[:50]}': {e}", exc_info=True)
|
||||
|
||||
return {"status": "success", "fetched": len(emails), "created": created, "attached": attached}
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Email fetch fatal error: {e}", exc_info=True)
|
||||
return {"status": "error", "fetched": 0, "created": 0, "attached": 0, "error": str(e)}
|
||||
finally:
|
||||
db.close()
|
||||
@@ -0,0 +1,51 @@
|
||||
"""SMS worker for Celery."""
|
||||
|
||||
from request_app.workers.celery_app import celery_app
|
||||
from request_app.core.database import SessionLocal
|
||||
from request_app.integrations.sms import SMSClient
|
||||
from request_app.models.ticket import Ticket
|
||||
from request_app.settings import get_settings
|
||||
|
||||
settings = get_settings()
|
||||
|
||||
|
||||
@celery_app.task(bind=True, max_retries=3)
|
||||
def send_sms_task(self, recipient: str, message: str):
|
||||
"""Send SMS task."""
|
||||
try:
|
||||
sms_client = SMSClient()
|
||||
result = sms_client.send_sms(recipient, message)
|
||||
|
||||
if result["status"] == "error":
|
||||
raise Exception(result["error"])
|
||||
|
||||
return {
|
||||
"status": "success",
|
||||
"recipient": recipient,
|
||||
"message": result
|
||||
}
|
||||
|
||||
except Exception as e:
|
||||
raise self.retry(exc=e, countdown=2 ** self.request.retries)
|
||||
|
||||
|
||||
@celery_app.task
|
||||
def send_ticket_created_sms(ticket_id: int, phone_number: str):
|
||||
"""Send SMS notification about ticket creation."""
|
||||
db = SessionLocal()
|
||||
|
||||
try:
|
||||
ticket = db.query(Ticket).filter(Ticket.id == ticket_id).first()
|
||||
if not ticket:
|
||||
return {"status": "error", "message": "Ticket not found"}
|
||||
|
||||
message = f"Тикет #{ticket_id} создан. Приоритет: {ticket.priority.name}, Статус: {ticket.status.name}"
|
||||
|
||||
send_sms_task.delay(phone_number, message)
|
||||
|
||||
return {"status": "success", "ticket_id": ticket_id, "phone": phone_number}
|
||||
|
||||
except Exception as e:
|
||||
return {"status": "error", "error": str(e)}
|
||||
finally:
|
||||
db.close()
|
||||
Reference in New Issue
Block a user