ервый импорт проекта
This commit is contained in:
@@ -0,0 +1,5 @@
|
||||
"""API routes package."""
|
||||
|
||||
from 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 app.core.database import get_db
|
||||
from app.core.auth import get_current_user
|
||||
from app.core.security import verify_password, create_local_token
|
||||
from 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 app.core.database import get_db
|
||||
from app.core.auth import get_current_user_id
|
||||
from app.core.exceptions import NotFoundException
|
||||
from app.schemas.email import (
|
||||
EmailMessageResponse,
|
||||
EmailMessageListResponse,
|
||||
SendEmailRequest,
|
||||
ForwardEmailRequest
|
||||
)
|
||||
from 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 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 app.core.database import get_db
|
||||
from app.core.auth import get_current_user_id
|
||||
from app.services.notification_service_extended import NotificationServiceExtended
|
||||
from 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 app.core.database import get_db
|
||||
from app.core.auth import get_current_user_id
|
||||
from app.schemas.reference import NotificationResponse, NotificationListResponse
|
||||
from 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 app.core.database import get_db
|
||||
from app.core.auth import get_current_user_id
|
||||
from app.core.exceptions import NotFoundException, ConflictException
|
||||
from app.schemas.reference import (
|
||||
StatusCreate, StatusResponse,
|
||||
PriorityCreate, PriorityResponse,
|
||||
CategoryCreate, CategoryResponse,
|
||||
CompanyCreate, CompanyResponse,
|
||||
LocationCreate, LocationResponse,
|
||||
DepartmentCreate, DepartmentResponse
|
||||
)
|
||||
from 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 app.core.database import get_db
|
||||
from app.core.auth import get_current_user_id
|
||||
from app.core.logging import logger
|
||||
from app.services.settings_service import SettingsService
|
||||
from 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 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 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 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 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 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 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 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 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 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 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 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 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 app.core.database import get_db
|
||||
from app.core.auth import get_current_user_id, get_current_user
|
||||
from app.core.exceptions import NotFoundException
|
||||
from app.schemas.ticket import (
|
||||
TicketCreate,
|
||||
TicketUpdate,
|
||||
TicketResponse,
|
||||
TicketListResponse,
|
||||
CommentCreate,
|
||||
CommentResponse
|
||||
)
|
||||
from app.schemas.common import PaginationParams
|
||||
from app.services.ticket_service import TicketService
|
||||
from 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 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 app.services.ticket_service import TicketService
|
||||
from app.services.email_message_service import EmailMessageService
|
||||
from 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 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 app.core.database import get_db
|
||||
from app.core.auth import get_current_user
|
||||
from app.core.security import get_password_hash, verify_password
|
||||
from app.models.user import User
|
||||
from app.models.role import Role
|
||||
from app.models.user_role import UserRole
|
||||
from 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 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 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 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"}
|
||||
Reference in New Issue
Block a user