Initial monorepo structure
@@ -0,0 +1,44 @@
|
||||
# Python
|
||||
__pycache__/
|
||||
*.pyc
|
||||
*.pyo
|
||||
*.db
|
||||
*.sqlite3
|
||||
.env
|
||||
venv/
|
||||
.pytest_cache/
|
||||
|
||||
# Frontend
|
||||
node_modules/
|
||||
dist/
|
||||
.vite/
|
||||
|
||||
# IDE
|
||||
.idea/
|
||||
.vscode/
|
||||
|
||||
# OS
|
||||
Thumbs.db
|
||||
.DS_Store
|
||||
|
||||
# Logs
|
||||
logs/
|
||||
*.log
|
||||
|
||||
# Вложения
|
||||
request-module/migrations/scripts/attachments/
|
||||
|
||||
# Документы
|
||||
*.pdf
|
||||
*.doc
|
||||
*.docx
|
||||
*.xls
|
||||
*.xlsx
|
||||
*.jpg
|
||||
*.jpeg
|
||||
*.png
|
||||
*.rar
|
||||
*.zip
|
||||
*.sig
|
||||
*.sec
|
||||
*.eml
|
||||
@@ -0,0 +1 @@
|
||||
"""App package."""
|
||||
@@ -0,0 +1 @@
|
||||
"""API package."""
|
||||
@@ -0,0 +1 @@
|
||||
"""API v1 package."""
|
||||
@@ -0,0 +1,101 @@
|
||||
"""Auth routes."""
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.core.database import get_db
|
||||
from app.core.security import get_password_hash, verify_password, create_access_token, decode_token
|
||||
from app.core.auth import get_current_user
|
||||
from app.models.user import User
|
||||
from app.models.associations import UserRole, UserModuleRole, ModuleRole
|
||||
from app.models.role import Role
|
||||
from app.schemas.schemas import RegisterRequest, LoginRequest, TokenResponse, UserResponse
|
||||
|
||||
router = APIRouter(prefix="/auth", tags=["Auth"])
|
||||
|
||||
|
||||
def _build_user_response(user: User, db: Session) -> dict:
|
||||
global_roles = [ur.role.name for ur in user.user_roles if ur.role]
|
||||
mod_roles = {}
|
||||
for umr in user.user_module_roles:
|
||||
if umr.module_role and umr.module_role.module:
|
||||
slug = umr.module_role.module.slug
|
||||
mod_roles.setdefault(slug, []).append(umr.module_role.role_name)
|
||||
return {
|
||||
"id": user.id,
|
||||
"email": user.email,
|
||||
"first_name": user.first_name,
|
||||
"last_name": user.last_name,
|
||||
"is_active": user.is_active,
|
||||
"is_superadmin": user.is_superadmin,
|
||||
"roles": global_roles,
|
||||
"module_roles": mod_roles,
|
||||
}
|
||||
|
||||
|
||||
@router.post("/register", response_model=UserResponse, status_code=201)
|
||||
async def register(data: RegisterRequest, db: Session = Depends(get_db)):
|
||||
if db.query(User).filter(User.email == data.email).first():
|
||||
raise HTTPException(status_code=409, detail="Email already registered")
|
||||
user = User(
|
||||
email=data.email,
|
||||
password_hash=get_password_hash(data.password),
|
||||
first_name=data.first_name,
|
||||
last_name=data.last_name,
|
||||
)
|
||||
db.add(user)
|
||||
db.commit()
|
||||
db.refresh(user)
|
||||
return _build_user_response(user, db)
|
||||
|
||||
|
||||
@router.post("/login", response_model=TokenResponse)
|
||||
async def login(data: LoginRequest, db: Session = Depends(get_db)):
|
||||
user = db.query(User).filter(User.email == data.email).first()
|
||||
if not user or not verify_password(data.password, user.password_hash):
|
||||
raise HTTPException(status_code=401, detail="Invalid email or password")
|
||||
if not user.is_active:
|
||||
raise HTTPException(status_code=403, detail="User is deactivated")
|
||||
|
||||
user_data = _build_user_response(user, db)
|
||||
token = create_access_token(data={
|
||||
"sub": str(user.id),
|
||||
"email": user.email,
|
||||
"first_name": user.first_name,
|
||||
"last_name": user.last_name,
|
||||
"is_active": user.is_active,
|
||||
"roles": user_data["roles"],
|
||||
"module_roles": user_data["module_roles"],
|
||||
})
|
||||
return {
|
||||
"access_token": token,
|
||||
"token_type": "bearer",
|
||||
"expires_in": 28800,
|
||||
"user": user_data,
|
||||
}
|
||||
|
||||
|
||||
@router.post("/validate")
|
||||
async def validate_token(token: str = None, db: Session = Depends(get_db)):
|
||||
"""Validate JWT for modules. Token passed as query param or body."""
|
||||
from fastapi import Request
|
||||
# Modules call this endpoint with the JWT
|
||||
# We just decode and return user data
|
||||
if not token:
|
||||
raise HTTPException(status_code=400, detail="Token required")
|
||||
payload = decode_token(token)
|
||||
if not payload:
|
||||
raise HTTPException(status_code=401, detail="Invalid token")
|
||||
user_id = payload.get("sub")
|
||||
if not user_id:
|
||||
raise HTTPException(status_code=401, detail="Invalid token")
|
||||
user = db.query(User).filter(User.id == int(user_id)).first()
|
||||
if not user:
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
user_data = _build_user_response(user, db)
|
||||
return {"user_id": user.id, **user_data}
|
||||
|
||||
|
||||
@router.get("/me")
|
||||
async def get_me(user: User = Depends(get_current_user), db: Session = Depends(get_db)):
|
||||
return _build_user_response(user, db)
|
||||
@@ -0,0 +1,10 @@
|
||||
"""Health routes."""
|
||||
|
||||
from fastapi import APIRouter
|
||||
|
||||
router = APIRouter(tags=["Health"])
|
||||
|
||||
|
||||
@router.get("/health")
|
||||
async def health():
|
||||
return {"status": "healthy", "service": "Platform"}
|
||||
@@ -0,0 +1,125 @@
|
||||
"""Modules routes."""
|
||||
|
||||
import secrets
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from sqlalchemy.orm import Session
|
||||
import httpx
|
||||
|
||||
from app.core.database import get_db
|
||||
from app.core.auth import require_platform_admin
|
||||
from app.models.user import User
|
||||
from app.models.module import Module
|
||||
from app.models.associations import ModuleRole
|
||||
from app.schemas.schemas import ModuleCreate, ModuleResponse, ModuleRoleResponse
|
||||
|
||||
router = APIRouter(prefix="/modules", tags=["Modules"])
|
||||
|
||||
|
||||
@router.get("")
|
||||
async def list_modules(db: Session = Depends(get_db)):
|
||||
modules = db.query(Module).order_by(Module.name).all()
|
||||
return [
|
||||
{
|
||||
"id": m.id, "name": m.name, "slug": m.slug, "description": m.description,
|
||||
"url": m.url, "icon": m.icon, "is_active": m.is_active,
|
||||
"roles_count": len(m.module_roles),
|
||||
}
|
||||
for m in modules
|
||||
]
|
||||
|
||||
|
||||
@router.post("", status_code=201)
|
||||
async def create_module(data: ModuleCreate, db: Session = Depends(get_db), admin: User = Depends(require_platform_admin)):
|
||||
if db.query(Module).filter(Module.slug == data.slug).first():
|
||||
raise HTTPException(status_code=409, detail="Module slug already exists")
|
||||
module = Module(
|
||||
name=data.name,
|
||||
slug=data.slug,
|
||||
description=data.description,
|
||||
url=data.url,
|
||||
icon=data.icon,
|
||||
api_key=secrets.token_hex(32),
|
||||
)
|
||||
db.add(module)
|
||||
db.commit()
|
||||
db.refresh(module)
|
||||
return {
|
||||
"id": module.id, "name": module.name, "slug": module.slug, "description": module.description,
|
||||
"url": module.url, "icon": module.icon, "is_active": module.is_active, "api_key": module.api_key,
|
||||
}
|
||||
|
||||
|
||||
@router.put("/{module_id}")
|
||||
async def update_module(module_id: int, data: ModuleCreate, db: Session = Depends(get_db), admin: User = Depends(require_platform_admin)):
|
||||
module = db.query(Module).filter(Module.id == module_id).first()
|
||||
if not module:
|
||||
raise HTTPException(status_code=404, detail="Module not found")
|
||||
module.name = data.name
|
||||
module.slug = data.slug
|
||||
module.description = data.description
|
||||
module.url = data.url
|
||||
module.icon = data.icon
|
||||
db.commit()
|
||||
return {
|
||||
"id": module.id, "name": module.name, "slug": module.slug, "description": module.description,
|
||||
"url": module.url, "icon": module.icon, "is_active": module.is_active, "api_key": module.api_key,
|
||||
}
|
||||
|
||||
|
||||
@router.delete("/{module_id}")
|
||||
async def delete_module(module_id: int, db: Session = Depends(get_db), admin: User = Depends(require_platform_admin)):
|
||||
module = db.query(Module).filter(Module.id == module_id).first()
|
||||
if not module:
|
||||
raise HTTPException(status_code=404, detail="Module not found")
|
||||
db.delete(module)
|
||||
db.commit()
|
||||
return {"message": "Module deleted"}
|
||||
|
||||
|
||||
@router.post("/{module_id}/sync-roles")
|
||||
async def sync_roles(module_id: int, db: Session = Depends(get_db), admin: User = Depends(require_platform_admin)):
|
||||
"""Import roles from module and sync all users."""
|
||||
module = db.query(Module).filter(Module.id == module_id).first()
|
||||
if not module:
|
||||
raise HTTPException(status_code=404, detail="Module not found")
|
||||
|
||||
# 1. Sync roles
|
||||
try:
|
||||
resp = httpx.get(f"{module.url.rstrip('/')}/api/v1/reference/roles", timeout=10)
|
||||
if resp.status_code != 200:
|
||||
raise HTTPException(status_code=502, detail=f"Module returned {resp.status_code}")
|
||||
roles_data = resp.json()
|
||||
except httpx.RequestError as e:
|
||||
raise HTTPException(status_code=502, detail=f"Cannot reach module: {e}")
|
||||
|
||||
# Clear old roles for this module
|
||||
db.query(ModuleRole).filter(ModuleRole.module_id == module_id).delete()
|
||||
|
||||
imported = 0
|
||||
for r in roles_data:
|
||||
role_name = r.get("name") if isinstance(r, dict) else r
|
||||
desc = r.get("description") if isinstance(r, dict) else None
|
||||
db.add(ModuleRole(module_id=module_id, role_name=role_name, description=desc))
|
||||
imported += 1
|
||||
|
||||
db.commit()
|
||||
|
||||
# 2. Sync all users to module
|
||||
from app.api.v1.users import _sync_all_users_to_modules
|
||||
_sync_all_users_to_modules(db)
|
||||
|
||||
return {
|
||||
"message": f"Imported {imported} roles and synced users",
|
||||
"roles": [r.get("name", r) if isinstance(r, dict) else r for r in roles_data],
|
||||
}
|
||||
|
||||
|
||||
@router.get("/{module_id}/roles")
|
||||
async def get_module_roles(module_id: int, db: Session = Depends(get_db)):
|
||||
module = db.query(Module).filter(Module.id == module_id).first()
|
||||
if not module:
|
||||
raise HTTPException(status_code=404, detail="Module not found")
|
||||
return [
|
||||
{"id": mr.id, "module_id": mr.module_id, "role_name": mr.role_name, "description": mr.description}
|
||||
for mr in module.module_roles
|
||||
]
|
||||
@@ -0,0 +1,54 @@
|
||||
"""Roles routes."""
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.core.database import get_db
|
||||
from app.core.auth import require_platform_admin
|
||||
from app.models.user import User
|
||||
from app.models.role import Role
|
||||
from app.schemas.schemas import RoleCreate, RoleResponse
|
||||
|
||||
router = APIRouter(prefix="/roles", tags=["Roles"])
|
||||
|
||||
|
||||
@router.get("")
|
||||
async def list_roles(db: Session = Depends(get_db)):
|
||||
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.post("", status_code=201)
|
||||
async def create_role(data: RoleCreate, db: Session = Depends(get_db), admin: User = Depends(require_platform_admin)):
|
||||
if db.query(Role).filter(Role.name == data.name).first():
|
||||
raise HTTPException(status_code=409, detail="Role already exists")
|
||||
role = Role(name=data.name, description=data.description)
|
||||
db.add(role)
|
||||
db.commit()
|
||||
db.refresh(role)
|
||||
return {"id": role.id, "name": role.name, "description": role.description, "is_system": role.is_system}
|
||||
|
||||
|
||||
@router.put("/{role_id}")
|
||||
async def update_role(role_id: int, data: RoleCreate, db: Session = Depends(get_db), admin: User = Depends(require_platform_admin)):
|
||||
role = db.query(Role).filter(Role.id == role_id).first()
|
||||
if not role:
|
||||
raise HTTPException(status_code=404, detail="Role not found")
|
||||
if role.is_system:
|
||||
raise HTTPException(status_code=400, detail="Cannot modify system role")
|
||||
role.name = data.name
|
||||
role.description = data.description
|
||||
db.commit()
|
||||
return {"id": role.id, "name": role.name, "description": role.description, "is_system": role.is_system}
|
||||
|
||||
|
||||
@router.delete("/{role_id}")
|
||||
async def delete_role(role_id: int, db: Session = Depends(get_db), admin: User = Depends(require_platform_admin)):
|
||||
role = db.query(Role).filter(Role.id == role_id).first()
|
||||
if not role:
|
||||
raise HTTPException(status_code=404, detail="Role not found")
|
||||
if role.is_system:
|
||||
raise HTTPException(status_code=400, detail="Cannot delete system role")
|
||||
db.delete(role)
|
||||
db.commit()
|
||||
return {"message": "Role deleted"}
|
||||
@@ -0,0 +1,309 @@
|
||||
"""Users routes."""
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from sqlalchemy.orm import Session
|
||||
from typing import Optional
|
||||
import httpx
|
||||
|
||||
from app.core.database import get_db
|
||||
from app.core.auth import get_current_user, require_platform_admin
|
||||
from app.core.security import get_password_hash, create_access_token
|
||||
from app.models.user import User
|
||||
from app.models.associations import UserRole, ModuleRole, UserModuleRole
|
||||
from app.models.role import Role
|
||||
from app.models.module import Module
|
||||
from app.schemas.schemas import UserResponse, UserListResponse, RoleResponse
|
||||
|
||||
router = APIRouter(prefix="/users", tags=["Users"])
|
||||
|
||||
|
||||
def _sync_user_to_modules(db: Session, user: User):
|
||||
"""Push user data to all active modules."""
|
||||
modules = db.query(Module).filter(Module.is_active == True).all()
|
||||
|
||||
# Build module roles mapping for this user
|
||||
module_roles = {}
|
||||
for umr in user.user_module_roles:
|
||||
if umr.module_role and umr.module_role.module:
|
||||
slug = umr.module_role.module.slug
|
||||
module_roles.setdefault(slug, []).append(umr.module_role.role_name)
|
||||
|
||||
for mod in modules:
|
||||
# Get roles specific to this module
|
||||
roles_for_module = module_roles.get(mod.slug, [])
|
||||
|
||||
user_data = {
|
||||
"id": user.id,
|
||||
"email": user.email,
|
||||
"first_name": user.first_name,
|
||||
"last_name": user.last_name,
|
||||
"is_active": user.is_active,
|
||||
"roles": roles_for_module,
|
||||
}
|
||||
|
||||
try:
|
||||
httpx.post(
|
||||
f"{mod.url.rstrip('/')}/api/v1/users/sync",
|
||||
json=user_data,
|
||||
headers={"X-API-Key": mod.api_key},
|
||||
timeout=5,
|
||||
)
|
||||
except Exception:
|
||||
pass # Module may be offline, that's OK
|
||||
|
||||
|
||||
def _sync_user_deletion_to_modules(db: Session, user: User):
|
||||
"""Notify modules about user deletion."""
|
||||
modules = db.query(Module).filter(Module.is_active == True).all()
|
||||
for mod in modules:
|
||||
try:
|
||||
httpx.delete(
|
||||
f"{mod.url.rstrip('/')}/api/v1/users/{user.id}",
|
||||
headers={"X-API-Key": mod.api_key},
|
||||
timeout=5,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _sync_all_users_to_modules(db: Session):
|
||||
"""Sync all users to all active modules."""
|
||||
modules = db.query(Module).filter(Module.is_active == True).all()
|
||||
users = db.query(User).filter(User.is_active == True).all()
|
||||
user_data_list = [
|
||||
{
|
||||
"id": u.id,
|
||||
"email": u.email,
|
||||
"first_name": u.first_name,
|
||||
"last_name": u.last_name,
|
||||
"is_active": u.is_active,
|
||||
}
|
||||
for u in users
|
||||
]
|
||||
for mod in modules:
|
||||
try:
|
||||
httpx.post(
|
||||
f"{mod.url.rstrip('/')}/api/v1/users/sync-all",
|
||||
json={"users": user_data_list},
|
||||
headers={"X-API-Key": mod.api_key},
|
||||
timeout=10,
|
||||
)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _build_user_response(user: User, db: Session) -> dict:
|
||||
global_roles = [ur.role.name for ur in user.user_roles if ur.role]
|
||||
mod_roles = {}
|
||||
for umr in user.user_module_roles:
|
||||
if umr.module_role and umr.module_role.module:
|
||||
slug = umr.module_role.module.slug
|
||||
mod_roles.setdefault(slug, []).append(umr.module_role.role_name)
|
||||
return {
|
||||
"id": user.id,
|
||||
"email": user.email,
|
||||
"first_name": user.first_name,
|
||||
"last_name": user.last_name,
|
||||
"is_active": user.is_active,
|
||||
"is_superadmin": user.is_superadmin,
|
||||
"roles": global_roles,
|
||||
"module_roles": mod_roles,
|
||||
}
|
||||
|
||||
|
||||
@router.get("", response_model=UserListResponse)
|
||||
async def list_users(
|
||||
page: int = Query(1, ge=1),
|
||||
page_size: int = Query(20, ge=1, le=100),
|
||||
search: Optional[str] = None,
|
||||
db: Session = Depends(get_db),
|
||||
admin: User = Depends(require_platform_admin),
|
||||
):
|
||||
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": [_build_user_response(u, db) for u in users],
|
||||
"total": total,
|
||||
"page": page,
|
||||
"page_size": page_size,
|
||||
"total_pages": (total + page_size - 1) // page_size,
|
||||
}
|
||||
|
||||
|
||||
@router.get("/me")
|
||||
async def get_me(user: User = Depends(get_current_user), db: Session = Depends(get_db)):
|
||||
return _build_user_response(user, db)
|
||||
|
||||
|
||||
@router.get("/{user_id}")
|
||||
async def get_user(user_id: int, db: Session = Depends(get_db), admin: User = Depends(require_platform_admin)):
|
||||
user = db.query(User).filter(User.id == user_id).first()
|
||||
if not user:
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
return _build_user_response(user, db)
|
||||
|
||||
|
||||
@router.post("", status_code=201)
|
||||
async def create_user(
|
||||
data: dict,
|
||||
db: Session = Depends(get_db),
|
||||
admin: User = Depends(require_platform_admin),
|
||||
):
|
||||
email = data.get("email")
|
||||
password = data.get("password")
|
||||
first_name = data.get("first_name", "")
|
||||
last_name = data.get("last_name", "")
|
||||
|
||||
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,
|
||||
password_hash=get_password_hash(password),
|
||||
first_name=first_name,
|
||||
last_name=last_name,
|
||||
is_active=True,
|
||||
is_superadmin=data.get("is_superadmin", False),
|
||||
)
|
||||
db.add(user)
|
||||
db.commit()
|
||||
db.refresh(user)
|
||||
|
||||
# Assign roles if provided
|
||||
for role_id in data.get("role_ids", []):
|
||||
db.add(UserRole(user_id=user.id, role_id=role_id))
|
||||
db.commit()
|
||||
db.refresh(user)
|
||||
|
||||
# Sync to modules
|
||||
_sync_user_to_modules(db, user)
|
||||
|
||||
return _build_user_response(user, db)
|
||||
|
||||
|
||||
@router.put("/{user_id}")
|
||||
async def update_user(
|
||||
user_id: int,
|
||||
data: dict,
|
||||
db: Session = Depends(get_db),
|
||||
admin: User = Depends(require_platform_admin),
|
||||
):
|
||||
user = db.query(User).filter(User.id == user_id).first()
|
||||
if not user:
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
|
||||
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 "is_active" in data:
|
||||
user.is_active = data["is_active"]
|
||||
if "is_superadmin" in data:
|
||||
user.is_superadmin = data["is_superadmin"]
|
||||
if "password" in data and data["password"]:
|
||||
user.password_hash = get_password_hash(data["password"])
|
||||
|
||||
db.commit()
|
||||
db.refresh(user)
|
||||
|
||||
# Sync to modules
|
||||
_sync_user_to_modules(db, user)
|
||||
|
||||
return _build_user_response(user, db)
|
||||
|
||||
|
||||
@router.delete("/{user_id}")
|
||||
async def delete_user(
|
||||
user_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
admin: User = Depends(require_platform_admin),
|
||||
):
|
||||
user = db.query(User).filter(User.id == user_id).first()
|
||||
if not user:
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
if user.is_superadmin:
|
||||
raise HTTPException(status_code=403, detail="Cannot delete superadmin")
|
||||
|
||||
# Notify modules about deletion
|
||||
_sync_user_deletion_to_modules(db, user)
|
||||
|
||||
db.delete(user)
|
||||
db.commit()
|
||||
return {"message": "User deleted"}
|
||||
|
||||
|
||||
@router.get("/{user_id}/roles")
|
||||
async def get_user_roles(user_id: int, db: Session = Depends(get_db)):
|
||||
user = db.query(User).filter(User.id == user_id).first()
|
||||
if not user:
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
return {"roles": [ur.role.name for ur in user.user_roles if ur.role]}
|
||||
|
||||
|
||||
@router.post("/{user_id}/roles/{role_id}")
|
||||
async def assign_role(user_id: int, role_id: int, db: Session = Depends(get_db), admin: User = Depends(require_platform_admin)):
|
||||
existing = db.query(UserRole).filter(UserRole.user_id == user_id, UserRole.role_id == role_id).first()
|
||||
if not existing:
|
||||
db.add(UserRole(user_id=user_id, role_id=role_id))
|
||||
db.commit()
|
||||
return {"message": "Role assigned"}
|
||||
|
||||
|
||||
@router.delete("/{user_id}/roles/{role_id}")
|
||||
async def remove_role(user_id: int, role_id: int, db: Session = Depends(get_db), admin: User = Depends(require_platform_admin)):
|
||||
ur = db.query(UserRole).filter(UserRole.user_id == user_id, UserRole.role_id == role_id).first()
|
||||
if ur:
|
||||
db.delete(ur)
|
||||
db.commit()
|
||||
return {"message": "Role removed"}
|
||||
|
||||
|
||||
@router.get("/{user_id}/module-roles")
|
||||
async def get_user_module_roles(user_id: int, db: Session = Depends(get_db), admin: User = Depends(require_platform_admin)):
|
||||
user = db.query(User).filter(User.id == user_id).first()
|
||||
if not user:
|
||||
raise HTTPException(status_code=404, detail="User not found")
|
||||
result = {}
|
||||
for umr in user.user_module_roles:
|
||||
if umr.module_role and umr.module_role.module:
|
||||
slug = umr.module_role.module.slug
|
||||
result.setdefault(slug, []).append(umr.module_role.role_name)
|
||||
return {"module_roles": result}
|
||||
|
||||
|
||||
@router.post("/{user_id}/module-roles/{module_role_id}")
|
||||
async def assign_module_role(user_id: int, module_role_id: int, db: Session = Depends(get_db), admin: User = Depends(require_platform_admin)):
|
||||
existing = db.query(UserModuleRole).filter(UserModuleRole.user_id == user_id, UserModuleRole.module_role_id == module_role_id).first()
|
||||
if not existing:
|
||||
db.add(UserModuleRole(user_id=user_id, module_role_id=module_role_id))
|
||||
db.commit()
|
||||
|
||||
# Sync user with updated roles to the module
|
||||
_sync_user_to_modules(db, db.query(User).filter(User.id == user_id).first())
|
||||
|
||||
return {"message": "Module role assigned"}
|
||||
|
||||
|
||||
@router.delete("/{user_id}/module-roles/{module_role_id}")
|
||||
async def remove_module_role(user_id: int, module_role_id: int, db: Session = Depends(get_db), admin: User = Depends(require_platform_admin)):
|
||||
umr = db.query(UserModuleRole).filter(UserModuleRole.user_id == user_id, UserModuleRole.module_role_id == module_role_id).first()
|
||||
if umr:
|
||||
db.delete(umr)
|
||||
db.commit()
|
||||
|
||||
# Sync user with updated roles to the module
|
||||
_sync_user_to_modules(db, db.query(User).filter(User.id == user_id).first())
|
||||
|
||||
return {"message": "Module role removed"}
|
||||
@@ -0,0 +1 @@
|
||||
"""Core package."""
|
||||
@@ -0,0 +1,47 @@
|
||||
"""Auth dependencies."""
|
||||
|
||||
from fastapi import Depends, HTTPException, status
|
||||
from fastapi.security import HTTPBearer, HTTPAuthorizationCredentials
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from app.core.database import get_db
|
||||
from app.core.security import decode_token
|
||||
from app.models.user import User
|
||||
|
||||
security = HTTPBearer()
|
||||
|
||||
|
||||
def get_current_user_id(credentials: HTTPAuthorizationCredentials = Depends(security)) -> int:
|
||||
token = credentials.credentials
|
||||
payload = decode_token(token)
|
||||
if not payload:
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token")
|
||||
user_id = payload.get("sub")
|
||||
if not user_id:
|
||||
raise HTTPException(status_code=status.HTTP_401_UNAUTHORIZED, detail="Invalid token")
|
||||
return int(user_id)
|
||||
|
||||
|
||||
def get_current_user(
|
||||
user_id: int = Depends(get_current_user_id),
|
||||
db: Session = Depends(get_db),
|
||||
) -> User:
|
||||
user = db.query(User).filter(User.id == user_id).first()
|
||||
if not user:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found")
|
||||
if not user.is_active:
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="User is deactivated")
|
||||
return user
|
||||
|
||||
|
||||
def require_platform_admin(user: User = Depends(get_current_user), db: Session = Depends(get_db)) -> User:
|
||||
if user.is_superadmin:
|
||||
return user
|
||||
from app.models.associations import UserRole
|
||||
from app.models.role import Role
|
||||
has_role = db.query(UserRole).join(Role).filter(
|
||||
UserRole.user_id == user.id, Role.name == "platform_admin"
|
||||
).first()
|
||||
if not has_role:
|
||||
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Platform admin required")
|
||||
return user
|
||||
@@ -0,0 +1,38 @@
|
||||
"""Database utilities."""
|
||||
|
||||
from sqlalchemy import create_engine
|
||||
from sqlalchemy.orm import sessionmaker, Session
|
||||
from typing import Generator
|
||||
from app.settings import get_settings
|
||||
from app.models.base import Base
|
||||
|
||||
settings = get_settings()
|
||||
engine = create_engine(settings.DATABASE_URL, pool_pre_ping=True, echo=False)
|
||||
SessionLocal = sessionmaker(autocommit=False, autoflush=False, bind=engine)
|
||||
|
||||
|
||||
def get_db() -> Generator[Session, None, None]:
|
||||
db = SessionLocal()
|
||||
try:
|
||||
yield db
|
||||
finally:
|
||||
db.close()
|
||||
|
||||
|
||||
def init_db():
|
||||
from app.models import user, role, module, associations
|
||||
Base.metadata.create_all(bind=engine)
|
||||
|
||||
db = SessionLocal()
|
||||
try:
|
||||
from app.models.role import Role
|
||||
system_roles = [
|
||||
("platform_admin", "Platform administrator", True),
|
||||
("user_manager", "Can manage users", True),
|
||||
]
|
||||
for name, desc, is_system in system_roles:
|
||||
if not db.query(Role).filter(Role.name == name).first():
|
||||
db.add(Role(name=name, description=desc, is_system=is_system))
|
||||
db.commit()
|
||||
finally:
|
||||
db.close()
|
||||
@@ -0,0 +1,32 @@
|
||||
"""Security utilities."""
|
||||
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Optional, Dict, Any
|
||||
from jose import JWTError, jwt
|
||||
import bcrypt
|
||||
from app.settings import get_settings
|
||||
|
||||
|
||||
def get_password_hash(password: str) -> str:
|
||||
return bcrypt.hashpw(password.encode("utf-8"), bcrypt.gensalt()).decode("utf-8")
|
||||
|
||||
|
||||
def verify_password(plain: str, hashed: str) -> bool:
|
||||
try:
|
||||
return bcrypt.checkpw(plain.encode("utf-8"), hashed.encode("utf-8"))
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def create_access_token(data: Dict[str, Any], expires_delta: Optional[timedelta] = None) -> str:
|
||||
to_encode = data.copy()
|
||||
expire = datetime.utcnow() + (expires_delta or timedelta(minutes=get_settings().JWT_ACCESS_TOKEN_EXPIRE_MINUTES))
|
||||
to_encode["exp"] = expire
|
||||
return jwt.encode(to_encode, get_settings().JWT_SECRET_KEY, algorithm=get_settings().JWT_ALGORITHM)
|
||||
|
||||
|
||||
def decode_token(token: str) -> Optional[Dict[str, Any]]:
|
||||
try:
|
||||
return jwt.decode(token, get_settings().JWT_SECRET_KEY, algorithms=[get_settings().JWT_ALGORITHM])
|
||||
except JWTError:
|
||||
return None
|
||||
@@ -0,0 +1,42 @@
|
||||
"""Platform - Main Application."""
|
||||
|
||||
from fastapi import FastAPI
|
||||
from fastapi.middleware.cors import CORSMiddleware
|
||||
from fastapi.responses import JSONResponse
|
||||
from app.settings import get_settings
|
||||
from app.core.database import init_db
|
||||
from app.api.v1 import auth, users, roles, modules, health
|
||||
|
||||
app = FastAPI(
|
||||
title=get_settings().APP_NAME,
|
||||
version=get_settings().APP_VERSION,
|
||||
description="Platform - Module Management System",
|
||||
openapi_url="/openapi.json",
|
||||
)
|
||||
|
||||
# CORS
|
||||
cors_origins = get_settings().APP_CORS_ORIGINS.split(",")
|
||||
app.add_middleware(
|
||||
CORSMiddleware,
|
||||
allow_origins=cors_origins,
|
||||
allow_credentials=True,
|
||||
allow_methods=["*"],
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
# Routes
|
||||
app.include_router(health.router, prefix="/api/v1")
|
||||
app.include_router(auth.router, prefix="/api/v1")
|
||||
app.include_router(users.router, prefix="/api/v1")
|
||||
app.include_router(roles.router, prefix="/api/v1")
|
||||
app.include_router(modules.router, prefix="/api/v1")
|
||||
|
||||
|
||||
@app.on_event("startup")
|
||||
async def startup():
|
||||
init_db()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import uvicorn
|
||||
uvicorn.run("app.main:app", host="0.0.0.0", port=9000, reload=True)
|
||||
@@ -0,0 +1 @@
|
||||
"""Models package."""
|
||||
@@ -0,0 +1,39 @@
|
||||
"""Association models."""
|
||||
|
||||
from sqlalchemy import Column, Integer, ForeignKey, String, Text
|
||||
from sqlalchemy.orm import relationship
|
||||
from app.models.base import Base, TimestampMixin
|
||||
|
||||
|
||||
class UserRole(Base, TimestampMixin):
|
||||
__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")
|
||||
|
||||
|
||||
class ModuleRole(Base, TimestampMixin):
|
||||
__tablename__ = "module_roles"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
module_id = Column(Integer, ForeignKey("modules.id", ondelete="CASCADE"), nullable=False)
|
||||
role_name = Column(String(100), nullable=False)
|
||||
description = Column(Text)
|
||||
|
||||
module = relationship("Module", back_populates="module_roles")
|
||||
user_module_roles = relationship("UserModuleRole", back_populates="module_role", cascade="all, delete-orphan")
|
||||
|
||||
|
||||
class UserModuleRole(Base, TimestampMixin):
|
||||
__tablename__ = "user_module_roles"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
user_id = Column(Integer, ForeignKey("users.id", ondelete="CASCADE"), nullable=False)
|
||||
module_role_id = Column(Integer, ForeignKey("module_roles.id", ondelete="CASCADE"), nullable=False)
|
||||
|
||||
user = relationship("User", back_populates="user_module_roles")
|
||||
module_role = relationship("ModuleRole", back_populates="user_module_roles")
|
||||
@@ -0,0 +1,12 @@
|
||||
"""Base model."""
|
||||
|
||||
from datetime import datetime
|
||||
from sqlalchemy import Column, DateTime, Integer
|
||||
from sqlalchemy.orm import declarative_base
|
||||
|
||||
Base = declarative_base()
|
||||
|
||||
|
||||
class TimestampMixin:
|
||||
created_at = Column(DateTime, default=datetime.utcnow, nullable=False)
|
||||
updated_at = Column(DateTime, default=datetime.utcnow, onupdate=datetime.utcnow, nullable=False)
|
||||
@@ -0,0 +1,20 @@
|
||||
"""Module model."""
|
||||
|
||||
from sqlalchemy import Column, String, Boolean, Text, Integer
|
||||
from sqlalchemy.orm import relationship
|
||||
from app.models.base import Base, TimestampMixin
|
||||
|
||||
|
||||
class Module(Base, TimestampMixin):
|
||||
__tablename__ = "modules"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
name = Column(String(100), nullable=False)
|
||||
slug = Column(String(50), unique=True, nullable=False)
|
||||
description = Column(Text)
|
||||
url = Column(String(500), nullable=False)
|
||||
icon = Column(String(50), default="Box")
|
||||
is_active = Column(Boolean, default=True)
|
||||
api_key = Column(String(64), unique=True)
|
||||
|
||||
module_roles = relationship("ModuleRole", back_populates="module", cascade="all, delete-orphan")
|
||||
@@ -0,0 +1,16 @@
|
||||
"""Role model."""
|
||||
|
||||
from sqlalchemy import Column, String, Boolean, Text, Integer
|
||||
from sqlalchemy.orm import relationship
|
||||
from app.models.base import Base, TimestampMixin
|
||||
|
||||
|
||||
class Role(Base, TimestampMixin):
|
||||
__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")
|
||||
@@ -0,0 +1,20 @@
|
||||
"""User model."""
|
||||
|
||||
from sqlalchemy import Column, String, Boolean, Integer
|
||||
from sqlalchemy.orm import relationship
|
||||
from app.models.base import Base, TimestampMixin
|
||||
|
||||
|
||||
class User(Base, TimestampMixin):
|
||||
__tablename__ = "users"
|
||||
|
||||
id = Column(Integer, primary_key=True, index=True)
|
||||
email = Column(String(255), unique=True, index=True, nullable=False)
|
||||
password_hash = Column(String(255), nullable=False)
|
||||
first_name = Column(String(100), nullable=False)
|
||||
last_name = Column(String(100), nullable=False)
|
||||
is_active = Column(Boolean, default=True)
|
||||
is_superadmin = Column(Boolean, default=False)
|
||||
|
||||
user_roles = relationship("UserRole", back_populates="user", cascade="all, delete-orphan")
|
||||
user_module_roles = relationship("UserModuleRole", back_populates="user", cascade="all, delete-orphan")
|
||||
@@ -0,0 +1 @@
|
||||
"""Schemas package."""
|
||||
@@ -0,0 +1,92 @@
|
||||
"""Auth schemas."""
|
||||
|
||||
from pydantic import BaseModel, EmailStr, Field
|
||||
from typing import Optional, List, Dict
|
||||
|
||||
|
||||
class RegisterRequest(BaseModel):
|
||||
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)
|
||||
|
||||
|
||||
class LoginRequest(BaseModel):
|
||||
email: EmailStr
|
||||
password: str
|
||||
|
||||
|
||||
class TokenResponse(BaseModel):
|
||||
access_token: str
|
||||
token_type: str = "bearer"
|
||||
expires_in: int
|
||||
user: dict
|
||||
|
||||
|
||||
class UserResponse(BaseModel):
|
||||
id: int
|
||||
email: str
|
||||
first_name: str
|
||||
last_name: str
|
||||
is_active: bool
|
||||
is_superadmin: bool
|
||||
roles: List[str] = []
|
||||
module_roles: Dict[str, List[str]] = {}
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
|
||||
class UserListResponse(BaseModel):
|
||||
users: List[UserResponse]
|
||||
total: int
|
||||
page: int
|
||||
page_size: int
|
||||
total_pages: int
|
||||
|
||||
|
||||
class RoleResponse(BaseModel):
|
||||
id: int
|
||||
name: str
|
||||
description: Optional[str]
|
||||
is_system: bool
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
|
||||
class RoleCreate(BaseModel):
|
||||
name: str = Field(..., min_length=1, max_length=100)
|
||||
description: Optional[str] = None
|
||||
|
||||
|
||||
class ModuleResponse(BaseModel):
|
||||
id: int
|
||||
name: str
|
||||
slug: str
|
||||
description: Optional[str]
|
||||
url: str
|
||||
icon: str
|
||||
is_active: bool
|
||||
api_key: str
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
|
||||
|
||||
class ModuleCreate(BaseModel):
|
||||
name: str = Field(..., min_length=1, max_length=100)
|
||||
slug: str = Field(..., min_length=1, max_length=50)
|
||||
description: Optional[str] = None
|
||||
url: str
|
||||
icon: str = "Box"
|
||||
|
||||
|
||||
class ModuleRoleResponse(BaseModel):
|
||||
id: int
|
||||
module_id: int
|
||||
role_name: str
|
||||
description: Optional[str]
|
||||
|
||||
class Config:
|
||||
from_attributes = True
|
||||
@@ -0,0 +1,24 @@
|
||||
"""Platform settings."""
|
||||
|
||||
from pydantic_settings import BaseSettings, SettingsConfigDict
|
||||
from functools import lru_cache
|
||||
|
||||
|
||||
class Settings(BaseSettings):
|
||||
model_config = SettingsConfigDict(env_file=".env", env_file_encoding="utf-8", case_sensitive=True)
|
||||
|
||||
APP_NAME: str = "Platform"
|
||||
APP_VERSION: str = "1.0.0"
|
||||
APP_DEBUG: bool = True
|
||||
APP_CORS_ORIGINS: str = "http://localhost:5173,http://localhost:5174,http://localhost:8000,http://localhost:8001"
|
||||
|
||||
DATABASE_URL: str = "sqlite:///./platform.db"
|
||||
|
||||
JWT_SECRET_KEY: str = "platform-secret-key-change-in-production"
|
||||
JWT_ALGORITHM: str = "HS256"
|
||||
JWT_ACCESS_TOKEN_EXPIRE_MINUTES: int = 480
|
||||
|
||||
|
||||
@lru_cache()
|
||||
def get_settings() -> Settings:
|
||||
return Settings()
|
||||
@@ -0,0 +1,10 @@
|
||||
fastapi==0.104.1
|
||||
uvicorn==0.24.0
|
||||
sqlalchemy==2.0.23
|
||||
pydantic==2.5.0
|
||||
pydantic-settings==2.1.0
|
||||
python-jose[cryptography]==3.3.0
|
||||
bcrypt==4.0.1
|
||||
httpx==0.25.2
|
||||
python-multipart==0.0.6
|
||||
email-validator==2.1.0
|
||||
@@ -0,0 +1,24 @@
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
lerna-debug.log*
|
||||
|
||||
node_modules
|
||||
dist
|
||||
dist-ssr
|
||||
*.local
|
||||
|
||||
# Editor directories and files
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
.idea
|
||||
.DS_Store
|
||||
*.suo
|
||||
*.ntvs*
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"$schema": "./node_modules/oxlint/configuration_schema.json",
|
||||
"plugins": ["react", "typescript", "oxc"],
|
||||
"rules": {
|
||||
"react/rules-of-hooks": "error",
|
||||
"react/only-export-components": ["warn", { "allowConstantExport": true }]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
# React + TypeScript + Vite
|
||||
|
||||
This template provides a minimal setup to get React working in Vite with HMR and some Oxlint rules.
|
||||
|
||||
Currently, two official plugins are available:
|
||||
|
||||
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Oxc](https://oxc.rs)
|
||||
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/)
|
||||
|
||||
## React Compiler
|
||||
|
||||
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
|
||||
|
||||
## Expanding the Oxlint configuration
|
||||
|
||||
If you are developing a production application, we recommend enabling type-aware lint rules by installing `oxlint-tsgolint` and editing `.oxlintrc.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"$schema": "./node_modules/oxlint/configuration_schema.json",
|
||||
"plugins": ["react", "typescript", "oxc"],
|
||||
"options": {
|
||||
"typeAware": true
|
||||
},
|
||||
"rules": {
|
||||
"react/rules-of-hooks": "error",
|
||||
"react/only-export-components": ["warn", { "allowConstantExport": true }]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
See the [Oxlint rules documentation](https://oxc.rs/docs/guide/usage/linter/rules) for the full list of rules and categories.
|
||||
@@ -0,0 +1,13 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>frontend-user</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,30 @@
|
||||
{
|
||||
"name": "frontend-user",
|
||||
"private": true,
|
||||
"version": "0.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc -b && vite build",
|
||||
"lint": "oxlint",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"@tailwindcss/vite": "^4.3.3",
|
||||
"axios": "^1.19.0",
|
||||
"lucide-react": "^1.28.0",
|
||||
"react": "^19.2.8",
|
||||
"react-dom": "^19.2.8",
|
||||
"react-router-dom": "^7.18.2",
|
||||
"tailwindcss": "^4.3.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^24.13.3",
|
||||
"@types/react": "^19.2.17",
|
||||
"@types/react-dom": "^19.2.3",
|
||||
"@vitejs/plugin-react": "^6.0.4",
|
||||
"oxlint": "^1.75.0",
|
||||
"typescript": "~6.0.2",
|
||||
"vite": "^8.2.0"
|
||||
}
|
||||
}
|
||||
|
After Width: | Height: | Size: 9.3 KiB |
@@ -0,0 +1,24 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg">
|
||||
<symbol id="bluesky-icon" viewBox="0 0 16 17">
|
||||
<g clip-path="url(#bluesky-clip)"><path fill="#08060d" d="M7.75 7.735c-.693-1.348-2.58-3.86-4.334-5.097-1.68-1.187-2.32-.981-2.74-.79C.188 2.065.1 2.812.1 3.251s.241 3.602.398 4.13c.52 1.744 2.367 2.333 4.07 2.145-2.495.37-4.71 1.278-1.805 4.512 3.196 3.309 4.38-.71 4.987-2.746.608 2.036 1.307 5.91 4.93 2.746 2.72-2.746.747-4.143-1.747-4.512 1.702.189 3.55-.4 4.07-2.145.156-.528.397-3.691.397-4.13s-.088-1.186-.575-1.406c-.42-.19-1.06-.395-2.741.79-1.755 1.24-3.64 3.752-4.334 5.099"/></g>
|
||||
<defs><clipPath id="bluesky-clip"><path fill="#fff" d="M.1.85h15.3v15.3H.1z"/></clipPath></defs>
|
||||
</symbol>
|
||||
<symbol id="discord-icon" viewBox="0 0 20 19">
|
||||
<path fill="#08060d" d="M16.224 3.768a14.5 14.5 0 0 0-3.67-1.153c-.158.286-.343.67-.47.976a13.5 13.5 0 0 0-4.067 0c-.128-.306-.317-.69-.476-.976A14.4 14.4 0 0 0 3.868 3.77C1.546 7.28.916 10.703 1.231 14.077a14.7 14.7 0 0 0 4.5 2.306q.545-.748.965-1.587a9.5 9.5 0 0 1-1.518-.74q.191-.14.372-.293c2.927 1.369 6.107 1.369 8.999 0q.183.152.372.294-.723.437-1.52.74.418.838.963 1.588a14.6 14.6 0 0 0 4.504-2.308c.37-3.911-.63-7.302-2.644-10.309m-9.13 8.234c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.894 0 1.614.82 1.599 1.82.001 1-.705 1.82-1.6 1.82m5.91 0c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.893 0 1.614.82 1.599 1.82 0 1-.706 1.82-1.6 1.82"/>
|
||||
</symbol>
|
||||
<symbol id="documentation-icon" viewBox="0 0 21 20">
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="m15.5 13.333 1.533 1.322c.645.555.967.833.967 1.178s-.322.623-.967 1.179L15.5 18.333m-3.333-5-1.534 1.322c-.644.555-.966.833-.966 1.178s.322.623.966 1.179l1.534 1.321"/>
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M17.167 10.836v-4.32c0-1.41 0-2.117-.224-2.68-.359-.906-1.118-1.621-2.08-1.96-.599-.21-1.349-.21-2.848-.21-2.623 0-3.935 0-4.983.369-1.684.591-3.013 1.842-3.641 3.428C3 6.449 3 7.684 3 10.154v2.122c0 2.558 0 3.838.706 4.726q.306.383.713.671c.76.536 1.79.64 3.581.66"/>
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M3 10a2.78 2.78 0 0 1 2.778-2.778c.555 0 1.209.097 1.748-.047.48-.129.854-.503.982-.982.145-.54.048-1.194.048-1.749a2.78 2.78 0 0 1 2.777-2.777"/>
|
||||
</symbol>
|
||||
<symbol id="github-icon" viewBox="0 0 19 19">
|
||||
<path fill="#08060d" fill-rule="evenodd" d="M9.356 1.85C5.05 1.85 1.57 5.356 1.57 9.694a7.84 7.84 0 0 0 5.324 7.44c.387.079.528-.168.528-.376 0-.182-.013-.805-.013-1.454-2.165.467-2.616-.935-2.616-.935-.349-.91-.864-1.143-.864-1.143-.71-.48.051-.48.051-.48.787.051 1.2.805 1.2.805.695 1.194 1.817.857 2.268.649.064-.507.27-.857.49-1.052-1.728-.182-3.545-.857-3.545-3.87 0-.857.31-1.558.8-2.104-.078-.195-.349-1 .077-2.078 0 0 .657-.208 2.14.805a7.5 7.5 0 0 1 1.946-.26c.657 0 1.328.092 1.946.26 1.483-1.013 2.14-.805 2.14-.805.426 1.078.155 1.883.078 2.078.502.546.799 1.247.799 2.104 0 3.013-1.818 3.675-3.558 3.87.284.247.528.714.528 1.454 0 1.052-.012 1.896-.012 2.156 0 .208.142.455.528.377a7.84 7.84 0 0 0 5.324-7.441c.013-4.338-3.48-7.844-7.773-7.844" clip-rule="evenodd"/>
|
||||
</symbol>
|
||||
<symbol id="social-icon" viewBox="0 0 20 20">
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M12.5 6.667a4.167 4.167 0 1 0-8.334 0 4.167 4.167 0 0 0 8.334 0"/>
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M2.5 16.667a5.833 5.833 0 0 1 8.75-5.053m3.837.474.513 1.035c.07.144.257.282.414.309l.93.155c.596.1.736.536.307.965l-.723.73a.64.64 0 0 0-.152.531l.207.903c.164.715-.213.991-.84.618l-.872-.52a.63.63 0 0 0-.577 0l-.872.52c-.624.373-1.003.094-.84-.618l.207-.903a.64.64 0 0 0-.152-.532l-.723-.729c-.426-.43-.289-.864.306-.964l.93-.156a.64.64 0 0 0 .412-.31l.513-1.034c.28-.562.735-.562 1.012 0"/>
|
||||
</symbol>
|
||||
<symbol id="x-icon" viewBox="0 0 19 19">
|
||||
<path fill="#08060d" fill-rule="evenodd" d="M1.893 1.98c.052.072 1.245 1.769 2.653 3.77l2.892 4.114c.183.261.333.48.333.486s-.068.089-.152.183l-.522.593-.765.867-3.597 4.087c-.375.426-.734.834-.798.905a1 1 0 0 0-.118.148c0 .01.236.017.664.017h.663l.729-.83c.4-.457.796-.906.879-.999a692 692 0 0 0 1.794-2.038c.034-.037.301-.34.594-.675l.551-.624.345-.392a7 7 0 0 1 .34-.374c.006 0 .93 1.306 2.052 2.903l2.084 2.965.045.063h2.275c1.87 0 2.273-.003 2.266-.021-.008-.02-1.098-1.572-3.894-5.547-2.013-2.862-2.28-3.246-2.273-3.266.008-.019.282-.332 2.085-2.38l2-2.274 1.567-1.782c.022-.028-.016-.03-.65-.03h-.674l-.3.342a871 871 0 0 1-1.782 2.025c-.067.075-.405.458-.75.852a100 100 0 0 1-.803.91c-.148.172-.299.344-.99 1.127-.304.343-.32.358-.345.327-.015-.019-.904-1.282-1.976-2.808L6.365 1.85H1.8zm1.782.91 8.078 11.294c.772 1.08 1.413 1.973 1.425 1.984.016.017.241.02 1.05.017l1.03-.004-2.694-3.766L7.796 5.75 5.722 2.852l-1.039-.004-1.039-.004z" clip-rule="evenodd"/>
|
||||
</symbol>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 4.9 KiB |
@@ -0,0 +1,184 @@
|
||||
.counter {
|
||||
font-size: 16px;
|
||||
padding: 5px 10px;
|
||||
border-radius: 5px;
|
||||
color: var(--accent);
|
||||
background: var(--accent-bg);
|
||||
border: 2px solid transparent;
|
||||
transition: border-color 0.3s;
|
||||
margin-bottom: 24px;
|
||||
|
||||
&:hover {
|
||||
border-color: var(--accent-border);
|
||||
}
|
||||
&:focus-visible {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
}
|
||||
|
||||
.hero {
|
||||
position: relative;
|
||||
|
||||
.base,
|
||||
.framework,
|
||||
.vite {
|
||||
inset-inline: 0;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
.base {
|
||||
width: 170px;
|
||||
position: relative;
|
||||
z-index: 0;
|
||||
}
|
||||
|
||||
.framework,
|
||||
.vite {
|
||||
position: absolute;
|
||||
}
|
||||
|
||||
.framework {
|
||||
z-index: 1;
|
||||
top: 34px;
|
||||
height: 28px;
|
||||
transform: perspective(2000px) rotateZ(300deg) rotateX(44deg) rotateY(39deg)
|
||||
scale(1.4);
|
||||
}
|
||||
|
||||
.vite {
|
||||
z-index: 0;
|
||||
top: 107px;
|
||||
height: 26px;
|
||||
width: auto;
|
||||
transform: perspective(2000px) rotateZ(300deg) rotateX(40deg) rotateY(39deg)
|
||||
scale(0.8);
|
||||
}
|
||||
}
|
||||
|
||||
#center {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 25px;
|
||||
place-content: center;
|
||||
place-items: center;
|
||||
flex-grow: 1;
|
||||
|
||||
@media (max-width: 1024px) {
|
||||
padding: 32px 20px 24px;
|
||||
gap: 18px;
|
||||
}
|
||||
}
|
||||
|
||||
#next-steps {
|
||||
display: flex;
|
||||
border-top: 1px solid var(--border);
|
||||
text-align: left;
|
||||
|
||||
& > div {
|
||||
flex: 1 1 0;
|
||||
padding: 32px;
|
||||
@media (max-width: 1024px) {
|
||||
padding: 24px 20px;
|
||||
}
|
||||
}
|
||||
|
||||
.icon {
|
||||
margin-bottom: 16px;
|
||||
width: 22px;
|
||||
height: 22px;
|
||||
}
|
||||
|
||||
@media (max-width: 1024px) {
|
||||
flex-direction: column;
|
||||
text-align: center;
|
||||
}
|
||||
}
|
||||
|
||||
#docs {
|
||||
border-right: 1px solid var(--border);
|
||||
|
||||
@media (max-width: 1024px) {
|
||||
border-right: none;
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
}
|
||||
|
||||
#next-steps ul {
|
||||
list-style: none;
|
||||
padding: 0;
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
margin: 32px 0 0;
|
||||
|
||||
.logo {
|
||||
height: 18px;
|
||||
}
|
||||
|
||||
a {
|
||||
color: var(--text-h);
|
||||
font-size: 16px;
|
||||
border-radius: 6px;
|
||||
background: var(--social-bg);
|
||||
display: flex;
|
||||
padding: 6px 12px;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
text-decoration: none;
|
||||
transition: box-shadow 0.3s;
|
||||
|
||||
&:hover {
|
||||
box-shadow: var(--shadow);
|
||||
}
|
||||
.button-icon {
|
||||
height: 18px;
|
||||
width: 18px;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 1024px) {
|
||||
margin-top: 20px;
|
||||
flex-wrap: wrap;
|
||||
justify-content: center;
|
||||
|
||||
li {
|
||||
flex: 1 1 calc(50% - 8px);
|
||||
}
|
||||
|
||||
a {
|
||||
width: 100%;
|
||||
justify-content: center;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#spacer {
|
||||
height: 88px;
|
||||
border-top: 1px solid var(--border);
|
||||
@media (max-width: 1024px) {
|
||||
height: 48px;
|
||||
}
|
||||
}
|
||||
|
||||
.ticks {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
|
||||
&::before,
|
||||
&::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: -4.5px;
|
||||
border: 5px solid transparent;
|
||||
}
|
||||
|
||||
&::before {
|
||||
left: 0;
|
||||
border-left-color: var(--border);
|
||||
}
|
||||
&::after {
|
||||
right: 0;
|
||||
border-right-color: var(--border);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { Routes, Route, Navigate } from 'react-router-dom'
|
||||
import { AuthProvider, useAuth } from './contexts/AuthContext'
|
||||
import Layout from './components/Layout'
|
||||
import Login from './pages/Login'
|
||||
import Register from './pages/Register'
|
||||
import Dashboard from './pages/Dashboard'
|
||||
import ModuleView from './pages/ModuleView'
|
||||
|
||||
function ProtectedRoute({ children }: { children: React.ReactNode }) {
|
||||
const { user, loading } = useAuth()
|
||||
if (loading) return <div className="flex items-center justify-center h-screen">Загрузка...</div>
|
||||
if (!user) return <Navigate to="/login" />
|
||||
return <>{children}</>
|
||||
}
|
||||
|
||||
export default function App() {
|
||||
return (
|
||||
<AuthProvider>
|
||||
<Routes>
|
||||
<Route path="/login" element={<Login />} />
|
||||
<Route path="/register" element={<Register />} />
|
||||
<Route path="/" element={<ProtectedRoute><Layout /></ProtectedRoute>}>
|
||||
<Route index element={<Dashboard />} />
|
||||
<Route path="module/:slug" element={<ModuleView />} />
|
||||
</Route>
|
||||
</Routes>
|
||||
</AuthProvider>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
import axios from 'axios'
|
||||
|
||||
const api = axios.create({ baseURL: '/api/v1' })
|
||||
|
||||
api.interceptors.request.use((config) => {
|
||||
const token = localStorage.getItem('platform_token')
|
||||
if (token) config.headers.Authorization = `Bearer ${token}`
|
||||
return config
|
||||
})
|
||||
|
||||
api.interceptors.response.use(
|
||||
(r) => r,
|
||||
(error) => {
|
||||
if (error.response?.status === 401) {
|
||||
localStorage.removeItem('platform_token')
|
||||
window.location.href = '/login'
|
||||
}
|
||||
return Promise.reject(error)
|
||||
}
|
||||
)
|
||||
|
||||
export const authApi = {
|
||||
login: (data: { email: string; password: string }) => api.post('/auth/login', data),
|
||||
register: (data: { email: string; password: string; first_name: string; last_name: string }) => api.post('/auth/register', data),
|
||||
me: () => api.get('/auth/me'),
|
||||
}
|
||||
|
||||
export const modulesApi = {
|
||||
list: () => api.get('/modules'),
|
||||
}
|
||||
|
||||
export default api
|
||||
|
After Width: | Height: | Size: 13 KiB |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>
|
||||
|
After Width: | Height: | Size: 4.0 KiB |
|
After Width: | Height: | Size: 8.5 KiB |
@@ -0,0 +1,66 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { Outlet, Link, useLocation, useNavigate } from 'react-router-dom'
|
||||
import { useAuth } from '../contexts/AuthContext'
|
||||
import { modulesApi } from '../api/client'
|
||||
import { Package, LogOut } from 'lucide-react'
|
||||
|
||||
export default function Layout() {
|
||||
const { user, logout } = useAuth()
|
||||
const location = useLocation()
|
||||
const navigate = useNavigate()
|
||||
const [modules, setModules] = useState<any[]>([])
|
||||
|
||||
const isModuleView = location.pathname.startsWith('/module/')
|
||||
|
||||
useEffect(() => {
|
||||
modulesApi.list().then(res => setModules(res.data.filter((m: any) => m.is_active))).catch(() => {})
|
||||
}, [])
|
||||
|
||||
const handleLogout = () => { logout(); navigate('/login') }
|
||||
|
||||
return (
|
||||
<div className="flex flex-col h-screen bg-gray-100">
|
||||
{/* Top header */}
|
||||
<header className="bg-white shadow-sm flex-shrink-0">
|
||||
<div className="flex items-center justify-between h-12 px-4">
|
||||
{/* Left: logo + home */}
|
||||
<div className="flex items-center gap-6">
|
||||
<Link to="/" className="text-lg font-bold text-gray-800 whitespace-nowrap">Платформа</Link>
|
||||
<Link to="/"
|
||||
className={`px-3 py-1.5 text-sm rounded-md transition-colors ${location.pathname === '/' ? 'bg-blue-50 text-blue-700 font-medium' : 'text-gray-600 hover:bg-gray-100'}`}>
|
||||
Мои модули
|
||||
</Link>
|
||||
</div>
|
||||
|
||||
{/* Center: module tabs */}
|
||||
{modules.length > 0 && (
|
||||
<div className="flex items-center gap-1">
|
||||
{modules.map(mod => (
|
||||
<Link key={mod.slug} to={`/module/${mod.slug}`}
|
||||
className={`px-3 py-1.5 text-sm rounded-md transition-colors flex items-center gap-1.5 ${location.pathname === `/module/${mod.slug}` ? 'bg-blue-600 text-white font-medium' : 'text-gray-600 hover:bg-gray-100'}`}>
|
||||
<Package className="w-3.5 h-3.5" />{mod.name}
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Right: logout */}
|
||||
<button onClick={handleLogout} className="flex items-center gap-1.5 px-3 py-1.5 text-sm text-gray-600 hover:bg-gray-100 rounded-md">
|
||||
<LogOut className="w-4 h-4" />Выход
|
||||
</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{/* Content */}
|
||||
<div className="flex-1 flex flex-col min-w-0 overflow-hidden">
|
||||
{isModuleView ? (
|
||||
<Outlet />
|
||||
) : (
|
||||
<div className="flex-1 overflow-auto p-6">
|
||||
<Outlet />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,62 @@
|
||||
import { createContext, useContext, useState, useEffect } from 'react'
|
||||
import type { ReactNode } from 'react'
|
||||
import { authApi } from '../api/client'
|
||||
|
||||
interface User {
|
||||
id: number
|
||||
email: string
|
||||
first_name: string
|
||||
last_name: string
|
||||
is_active: boolean
|
||||
roles: string[]
|
||||
module_roles: Record<string, string[]>
|
||||
}
|
||||
|
||||
interface AuthContextType {
|
||||
user: User | null
|
||||
loading: boolean
|
||||
login: (email: string, password: string) => Promise<void>
|
||||
logout: () => void
|
||||
}
|
||||
|
||||
const AuthContext = createContext<AuthContextType | undefined>(undefined)
|
||||
|
||||
export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
const [user, setUser] = useState<User | null>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
|
||||
useEffect(() => {
|
||||
const token = localStorage.getItem('platform_token')
|
||||
if (token) {
|
||||
authApi.me()
|
||||
.then(res => setUser(res.data))
|
||||
.catch(() => localStorage.removeItem('platform_token'))
|
||||
.finally(() => setLoading(false))
|
||||
} else {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [])
|
||||
|
||||
const login = async (email: string, password: string) => {
|
||||
const res = await authApi.login({ email, password })
|
||||
localStorage.setItem('platform_token', res.data.access_token)
|
||||
setUser(res.data.user)
|
||||
}
|
||||
|
||||
const logout = () => {
|
||||
localStorage.removeItem('platform_token')
|
||||
setUser(null)
|
||||
}
|
||||
|
||||
return (
|
||||
<AuthContext.Provider value={{ user, loading, login, logout }}>
|
||||
{children}
|
||||
</AuthContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
export function useAuth() {
|
||||
const ctx = useContext(AuthContext)
|
||||
if (!ctx) throw new Error('useAuth must be inside AuthProvider')
|
||||
return ctx
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
@import "tailwindcss";
|
||||
@@ -0,0 +1,13 @@
|
||||
import { StrictMode } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import { BrowserRouter } from 'react-router-dom'
|
||||
import App from './App'
|
||||
import './index.css'
|
||||
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<StrictMode>
|
||||
<BrowserRouter>
|
||||
<App />
|
||||
</BrowserRouter>
|
||||
</StrictMode>,
|
||||
)
|
||||
@@ -0,0 +1,58 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { Link } from 'react-router-dom'
|
||||
import { modulesApi } from '../api/client'
|
||||
import { useAuth } from '../contexts/AuthContext'
|
||||
import { Package, ExternalLink } from 'lucide-react'
|
||||
|
||||
export default function Dashboard() {
|
||||
const { user } = useAuth()
|
||||
const [modules, setModules] = useState<any[]>([])
|
||||
|
||||
useEffect(() => {
|
||||
modulesApi.list().then(res => setModules(res.data.filter((m: any) => m.is_active))).catch(() => {})
|
||||
}, [])
|
||||
|
||||
return (
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-gray-900 mb-2">Добро пожаловать, {user?.first_name}!</h1>
|
||||
<p className="text-gray-500 mb-8">Выберите модуль для работы</p>
|
||||
|
||||
{modules.length === 0 ? (
|
||||
<div className="bg-white rounded-lg shadow p-8 text-center">
|
||||
<Package className="w-12 h-12 text-gray-300 mx-auto mb-4" />
|
||||
<p className="text-gray-500">Нет доступных модулей</p>
|
||||
<p className="text-sm text-gray-400 mt-1">Обратитесь к администратору для подключения модулей</p>
|
||||
</div>
|
||||
) : (
|
||||
<div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
|
||||
{modules.map(mod => {
|
||||
const userRoles = user?.module_roles?.[mod.slug] || []
|
||||
return (
|
||||
<Link key={mod.slug} to={`/module/${mod.slug}`}
|
||||
className="bg-white rounded-lg shadow hover:shadow-md transition-shadow p-6 group">
|
||||
<div className="flex items-start justify-between mb-4">
|
||||
<div className="w-12 h-12 bg-blue-100 rounded-lg flex items-center justify-center">
|
||||
<Package className="w-6 h-6 text-blue-600" />
|
||||
</div>
|
||||
<ExternalLink className="w-4 h-4 text-gray-400 group-hover:text-blue-600 transition-colors" />
|
||||
</div>
|
||||
<h3 className="font-semibold text-lg text-gray-900 mb-1">{mod.name}</h3>
|
||||
<p className="text-sm text-gray-500 mb-3">{mod.description || 'Без описания'}</p>
|
||||
{userRoles.length > 0 && (
|
||||
<div className="flex gap-1 flex-wrap">
|
||||
{userRoles.map((r: string) => (
|
||||
<span key={r} className="px-2 py-0.5 text-xs bg-green-100 text-green-800 rounded-full">{r}</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
{userRoles.length === 0 && (
|
||||
<span className="text-xs text-gray-400">Нет ролей в модуле</span>
|
||||
)}
|
||||
</Link>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,52 @@
|
||||
import { useState } from 'react'
|
||||
import { useNavigate, Link } from 'react-router-dom'
|
||||
import { useAuth } from '../contexts/AuthContext'
|
||||
|
||||
export default function Login() {
|
||||
const [email, setEmail] = useState('')
|
||||
const [password, setPassword] = useState('')
|
||||
const [error, setError] = useState('')
|
||||
const [loading, setLoading] = useState(false)
|
||||
const { login } = useAuth()
|
||||
const navigate = useNavigate()
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
setError('')
|
||||
setLoading(true)
|
||||
try {
|
||||
await login(email, password)
|
||||
navigate('/')
|
||||
} catch (err: any) {
|
||||
setError(err.response?.data?.detail || 'Ошибка входа')
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-gray-100">
|
||||
<div className="bg-white p-8 rounded-lg shadow-md w-full max-w-md">
|
||||
<h1 className="text-2xl font-bold text-center mb-6">Платформа</h1>
|
||||
<h2 className="text-lg text-gray-600 text-center mb-8">Войдите в аккаунт</h2>
|
||||
{error && <div className="bg-red-50 text-red-600 p-3 rounded-lg mb-4 text-sm">{error}</div>}
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">Email</label>
|
||||
<input type="email" value={email} onChange={e => setEmail(e.target.value)} className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" required />
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">Пароль</label>
|
||||
<input type="password" value={password} onChange={e => setPassword(e.target.value)} className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" required />
|
||||
</div>
|
||||
<button type="submit" disabled={loading} className="w-full py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50">
|
||||
{loading ? 'Вход...' : 'Войти'}
|
||||
</button>
|
||||
</form>
|
||||
<p className="mt-4 text-center text-sm text-gray-600">
|
||||
Нет аккаунта? <Link to="/register" className="text-blue-600 hover:underline">Регистрация</Link>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,115 @@
|
||||
import { useState, useEffect, useRef } from 'react'
|
||||
import { useParams } from 'react-router-dom'
|
||||
import { modulesApi } from '../api/client'
|
||||
import { ExternalLink, Loader2 } from 'lucide-react'
|
||||
|
||||
export default function ModuleView() {
|
||||
const { slug } = useParams()
|
||||
const [module, setModule] = useState<any>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [iframeLoading, setIframeLoading] = useState(true)
|
||||
const [moduleUrl, setModuleUrl] = useState('')
|
||||
const iframeRef = useRef<HTMLIFrameElement>(null)
|
||||
|
||||
useEffect(() => {
|
||||
modulesApi.list().then(res => {
|
||||
const found = res.data.find((m: any) => m.slug === slug)
|
||||
setModule(found)
|
||||
}).finally(() => setLoading(false))
|
||||
}, [slug])
|
||||
|
||||
useEffect(() => {
|
||||
if (!module) return
|
||||
|
||||
const getToken = () => localStorage.getItem('platform_token') || ''
|
||||
|
||||
const updateUrl = () => {
|
||||
const token = getToken()
|
||||
const url = `${module.url}?token=${encodeURIComponent(token)}`
|
||||
setModuleUrl(url)
|
||||
}
|
||||
|
||||
const sendTokenToIframe = () => {
|
||||
const token = getToken()
|
||||
const iframe = iframeRef.current
|
||||
if (iframe?.contentWindow) {
|
||||
iframe.contentWindow.postMessage(
|
||||
{ type: 'PLATFORM_TOKEN_UPDATE', token },
|
||||
module.url
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
updateUrl()
|
||||
|
||||
const handleStorage = (e: StorageEvent) => {
|
||||
if (e.key === 'platform_token') {
|
||||
updateUrl()
|
||||
sendTokenToIframe()
|
||||
}
|
||||
}
|
||||
window.addEventListener('storage', handleStorage)
|
||||
|
||||
let lastToken = getToken()
|
||||
const interval = setInterval(() => {
|
||||
const currentToken = getToken()
|
||||
if (currentToken !== lastToken) {
|
||||
lastToken = currentToken
|
||||
updateUrl()
|
||||
sendTokenToIframe()
|
||||
}
|
||||
}, 10000)
|
||||
|
||||
return () => {
|
||||
window.removeEventListener('storage', handleStorage)
|
||||
clearInterval(interval)
|
||||
}
|
||||
}, [module])
|
||||
|
||||
useEffect(() => {
|
||||
setIframeLoading(true)
|
||||
}, [slug])
|
||||
|
||||
if (loading) return (
|
||||
<div className="flex-1 flex items-center justify-center">
|
||||
<Loader2 className="w-8 h-8 animate-spin text-blue-500" />
|
||||
</div>
|
||||
)
|
||||
|
||||
if (!module) return (
|
||||
<div className="flex-1 flex items-center justify-center">
|
||||
<p className="text-gray-500">Модуль не найден</p>
|
||||
</div>
|
||||
)
|
||||
|
||||
return (
|
||||
<div className="flex-1 flex flex-col h-full">
|
||||
<div className="flex items-center justify-between px-6 py-3 bg-white border-b flex-shrink-0">
|
||||
<h1 className="text-lg font-semibold text-gray-900">{module.name}</h1>
|
||||
<a href={moduleUrl} target="_blank" rel="noopener noreferrer"
|
||||
className="flex items-center gap-1 text-sm text-blue-600 hover:text-blue-800">
|
||||
<ExternalLink className="w-4 h-4" />Открыть отдельно
|
||||
</a>
|
||||
</div>
|
||||
<div className="flex-1 relative">
|
||||
{iframeLoading && (
|
||||
<div className="absolute inset-0 flex items-center justify-center bg-gray-50 z-10">
|
||||
<div className="text-center">
|
||||
<Loader2 className="w-8 h-8 animate-spin text-blue-500 mx-auto mb-2" />
|
||||
<p className="text-sm text-gray-500">Загрузка модуля...</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{moduleUrl && (
|
||||
<iframe
|
||||
ref={iframeRef}
|
||||
src={moduleUrl}
|
||||
className="w-full h-full border-0"
|
||||
title={module.name}
|
||||
onLoad={() => setIframeLoading(false)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import { useState } from 'react'
|
||||
import { useNavigate, Link } from 'react-router-dom'
|
||||
import { authApi } from '../api/client'
|
||||
|
||||
export default function Register() {
|
||||
const [form, setForm] = useState({ email: '', password: '', first_name: '', last_name: '' })
|
||||
const [error, setError] = useState('')
|
||||
const [loading, setLoading] = useState(false)
|
||||
const navigate = useNavigate()
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
setError('')
|
||||
setLoading(true)
|
||||
try {
|
||||
await authApi.register(form)
|
||||
navigate('/login')
|
||||
} catch (err: any) {
|
||||
setError(err.response?.data?.detail || 'Ошибка регистрации')
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-gray-100">
|
||||
<div className="bg-white p-8 rounded-lg shadow-md w-full max-w-md">
|
||||
<h1 className="text-2xl font-bold text-center mb-6">Платформа</h1>
|
||||
<h2 className="text-lg text-gray-600 text-center mb-8">Регистрация</h2>
|
||||
{error && <div className="bg-red-50 text-red-600 p-3 rounded-lg mb-4 text-sm">{error}</div>}
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">Имя</label>
|
||||
<input type="text" value={form.first_name} onChange={e => setForm({...form, first_name: e.target.value})} className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" required />
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">Фамилия</label>
|
||||
<input type="text" value={form.last_name} onChange={e => setForm({...form, last_name: e.target.value})} className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" required />
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">Email</label>
|
||||
<input type="email" value={form.email} onChange={e => setForm({...form, email: e.target.value})} className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" required />
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">Пароль</label>
|
||||
<input type="password" value={form.password} onChange={e => setForm({...form, password: e.target.value})} className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" required minLength={6} />
|
||||
</div>
|
||||
<button type="submit" disabled={loading} className="w-full py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50">
|
||||
{loading ? 'Регистрация...' : 'Зарегистрироваться'}
|
||||
</button>
|
||||
</form>
|
||||
<p className="mt-4 text-center text-sm text-gray-600">
|
||||
Уже есть аккаунт? <Link to="/login" className="text-blue-600 hover:underline">Войти</Link>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
|
||||
"target": "es2023",
|
||||
"lib": ["ES2023", "DOM"],
|
||||
"module": "esnext",
|
||||
"types": ["vite/client"],
|
||||
"allowArbitraryExtensions": true,
|
||||
"skipLibCheck": true,
|
||||
|
||||
/* Bundler mode */
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
"jsx": "react-jsx",
|
||||
|
||||
/* Linting */
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"erasableSyntaxOnly": true,
|
||||
"noFallthroughCasesInSwitch": true
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"files": [],
|
||||
"references": [
|
||||
{ "path": "./tsconfig.app.json" },
|
||||
{ "path": "./tsconfig.node.json" }
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
|
||||
"target": "es2023",
|
||||
"lib": ["ES2023"],
|
||||
"types": ["node"],
|
||||
"skipLibCheck": true,
|
||||
|
||||
/* Bundler mode */
|
||||
"module": "nodenext",
|
||||
"allowImportingTsExtensions": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
|
||||
/* Linting */
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"erasableSyntaxOnly": true,
|
||||
"noFallthroughCasesInSwitch": true
|
||||
},
|
||||
"include": ["vite.config.ts"]
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { defineConfig } from 'vite'
|
||||
import react from '@vitejs/plugin-react'
|
||||
import tailwindcss from '@tailwindcss/vite'
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [react(), tailwindcss()],
|
||||
server: {
|
||||
port: 5175,
|
||||
proxy: {
|
||||
'/api': 'http://localhost:8001',
|
||||
},
|
||||
},
|
||||
})
|
||||
@@ -0,0 +1,24 @@
|
||||
# Logs
|
||||
logs
|
||||
*.log
|
||||
npm-debug.log*
|
||||
yarn-debug.log*
|
||||
yarn-error.log*
|
||||
pnpm-debug.log*
|
||||
lerna-debug.log*
|
||||
|
||||
node_modules
|
||||
dist
|
||||
dist-ssr
|
||||
*.local
|
||||
|
||||
# Editor directories and files
|
||||
.vscode/*
|
||||
!.vscode/extensions.json
|
||||
.idea
|
||||
.DS_Store
|
||||
*.suo
|
||||
*.ntvs*
|
||||
*.njsproj
|
||||
*.sln
|
||||
*.sw?
|
||||
@@ -0,0 +1,8 @@
|
||||
{
|
||||
"$schema": "./node_modules/oxlint/configuration_schema.json",
|
||||
"plugins": ["react", "typescript", "oxc"],
|
||||
"rules": {
|
||||
"react/rules-of-hooks": "error",
|
||||
"react/only-export-components": ["warn", { "allowConstantExport": true }]
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
# React + TypeScript + Vite
|
||||
|
||||
This template provides a minimal setup to get React working in Vite with HMR and some Oxlint rules.
|
||||
|
||||
Currently, two official plugins are available:
|
||||
|
||||
- [@vitejs/plugin-react](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react) uses [Oxc](https://oxc.rs)
|
||||
- [@vitejs/plugin-react-swc](https://github.com/vitejs/vite-plugin-react/blob/main/packages/plugin-react-swc) uses [SWC](https://swc.rs/)
|
||||
|
||||
## React Compiler
|
||||
|
||||
The React Compiler is not enabled on this template because of its impact on dev & build performances. To add it, see [this documentation](https://react.dev/learn/react-compiler/installation).
|
||||
|
||||
## Expanding the Oxlint configuration
|
||||
|
||||
If you are developing a production application, we recommend enabling type-aware lint rules by installing `oxlint-tsgolint` and editing `.oxlintrc.json`:
|
||||
|
||||
```json
|
||||
{
|
||||
"$schema": "./node_modules/oxlint/configuration_schema.json",
|
||||
"plugins": ["react", "typescript", "oxc"],
|
||||
"options": {
|
||||
"typeAware": true
|
||||
},
|
||||
"rules": {
|
||||
"react/rules-of-hooks": "error",
|
||||
"react/only-export-components": ["warn", { "allowConstantExport": true }]
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
See the [Oxlint rules documentation](https://oxc.rs/docs/guide/usage/linter/rules) for the full list of rules and categories.
|
||||
@@ -0,0 +1,13 @@
|
||||
<!doctype html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<link rel="icon" type="image/svg+xml" href="/favicon.svg" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>frontend</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="root"></div>
|
||||
<script type="module" src="/src/main.tsx"></script>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,30 @@
|
||||
{
|
||||
"name": "frontend",
|
||||
"private": true,
|
||||
"version": "0.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "tsc -b && vite build",
|
||||
"lint": "oxlint",
|
||||
"preview": "vite preview"
|
||||
},
|
||||
"dependencies": {
|
||||
"@tailwindcss/vite": "^4.3.3",
|
||||
"axios": "^1.19.0",
|
||||
"lucide-react": "^1.28.0",
|
||||
"react": "^19.2.8",
|
||||
"react-dom": "^19.2.8",
|
||||
"react-router-dom": "^7.18.2",
|
||||
"tailwindcss": "^4.3.3"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@types/node": "^24.13.3",
|
||||
"@types/react": "^19.2.17",
|
||||
"@types/react-dom": "^19.2.3",
|
||||
"@vitejs/plugin-react": "^6.0.4",
|
||||
"oxlint": "^1.75.0",
|
||||
"typescript": "~6.0.2",
|
||||
"vite": "^8.2.0"
|
||||
}
|
||||
}
|
||||
|
After Width: | Height: | Size: 9.3 KiB |
@@ -0,0 +1,24 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg">
|
||||
<symbol id="bluesky-icon" viewBox="0 0 16 17">
|
||||
<g clip-path="url(#bluesky-clip)"><path fill="#08060d" d="M7.75 7.735c-.693-1.348-2.58-3.86-4.334-5.097-1.68-1.187-2.32-.981-2.74-.79C.188 2.065.1 2.812.1 3.251s.241 3.602.398 4.13c.52 1.744 2.367 2.333 4.07 2.145-2.495.37-4.71 1.278-1.805 4.512 3.196 3.309 4.38-.71 4.987-2.746.608 2.036 1.307 5.91 4.93 2.746 2.72-2.746.747-4.143-1.747-4.512 1.702.189 3.55-.4 4.07-2.145.156-.528.397-3.691.397-4.13s-.088-1.186-.575-1.406c-.42-.19-1.06-.395-2.741.79-1.755 1.24-3.64 3.752-4.334 5.099"/></g>
|
||||
<defs><clipPath id="bluesky-clip"><path fill="#fff" d="M.1.85h15.3v15.3H.1z"/></clipPath></defs>
|
||||
</symbol>
|
||||
<symbol id="discord-icon" viewBox="0 0 20 19">
|
||||
<path fill="#08060d" d="M16.224 3.768a14.5 14.5 0 0 0-3.67-1.153c-.158.286-.343.67-.47.976a13.5 13.5 0 0 0-4.067 0c-.128-.306-.317-.69-.476-.976A14.4 14.4 0 0 0 3.868 3.77C1.546 7.28.916 10.703 1.231 14.077a14.7 14.7 0 0 0 4.5 2.306q.545-.748.965-1.587a9.5 9.5 0 0 1-1.518-.74q.191-.14.372-.293c2.927 1.369 6.107 1.369 8.999 0q.183.152.372.294-.723.437-1.52.74.418.838.963 1.588a14.6 14.6 0 0 0 4.504-2.308c.37-3.911-.63-7.302-2.644-10.309m-9.13 8.234c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.894 0 1.614.82 1.599 1.82.001 1-.705 1.82-1.6 1.82m5.91 0c-.878 0-1.599-.82-1.599-1.82 0-.998.705-1.82 1.6-1.82.893 0 1.614.82 1.599 1.82 0 1-.706 1.82-1.6 1.82"/>
|
||||
</symbol>
|
||||
<symbol id="documentation-icon" viewBox="0 0 21 20">
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="m15.5 13.333 1.533 1.322c.645.555.967.833.967 1.178s-.322.623-.967 1.179L15.5 18.333m-3.333-5-1.534 1.322c-.644.555-.966.833-.966 1.178s.322.623.966 1.179l1.534 1.321"/>
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M17.167 10.836v-4.32c0-1.41 0-2.117-.224-2.68-.359-.906-1.118-1.621-2.08-1.96-.599-.21-1.349-.21-2.848-.21-2.623 0-3.935 0-4.983.369-1.684.591-3.013 1.842-3.641 3.428C3 6.449 3 7.684 3 10.154v2.122c0 2.558 0 3.838.706 4.726q.306.383.713.671c.76.536 1.79.64 3.581.66"/>
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M3 10a2.78 2.78 0 0 1 2.778-2.778c.555 0 1.209.097 1.748-.047.48-.129.854-.503.982-.982.145-.54.048-1.194.048-1.749a2.78 2.78 0 0 1 2.777-2.777"/>
|
||||
</symbol>
|
||||
<symbol id="github-icon" viewBox="0 0 19 19">
|
||||
<path fill="#08060d" fill-rule="evenodd" d="M9.356 1.85C5.05 1.85 1.57 5.356 1.57 9.694a7.84 7.84 0 0 0 5.324 7.44c.387.079.528-.168.528-.376 0-.182-.013-.805-.013-1.454-2.165.467-2.616-.935-2.616-.935-.349-.91-.864-1.143-.864-1.143-.71-.48.051-.48.051-.48.787.051 1.2.805 1.2.805.695 1.194 1.817.857 2.268.649.064-.507.27-.857.49-1.052-1.728-.182-3.545-.857-3.545-3.87 0-.857.31-1.558.8-2.104-.078-.195-.349-1 .077-2.078 0 0 .657-.208 2.14.805a7.5 7.5 0 0 1 1.946-.26c.657 0 1.328.092 1.946.26 1.483-1.013 2.14-.805 2.14-.805.426 1.078.155 1.883.078 2.078.502.546.799 1.247.799 2.104 0 3.013-1.818 3.675-3.558 3.87.284.247.528.714.528 1.454 0 1.052-.012 1.896-.012 2.156 0 .208.142.455.528.377a7.84 7.84 0 0 0 5.324-7.441c.013-4.338-3.48-7.844-7.773-7.844" clip-rule="evenodd"/>
|
||||
</symbol>
|
||||
<symbol id="social-icon" viewBox="0 0 20 20">
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M12.5 6.667a4.167 4.167 0 1 0-8.334 0 4.167 4.167 0 0 0 8.334 0"/>
|
||||
<path fill="none" stroke="#aa3bff" stroke-linecap="round" stroke-linejoin="round" stroke-width="1.35" d="M2.5 16.667a5.833 5.833 0 0 1 8.75-5.053m3.837.474.513 1.035c.07.144.257.282.414.309l.93.155c.596.1.736.536.307.965l-.723.73a.64.64 0 0 0-.152.531l.207.903c.164.715-.213.991-.84.618l-.872-.52a.63.63 0 0 0-.577 0l-.872.52c-.624.373-1.003.094-.84-.618l.207-.903a.64.64 0 0 0-.152-.532l-.723-.729c-.426-.43-.289-.864.306-.964l.93-.156a.64.64 0 0 0 .412-.31l.513-1.034c.28-.562.735-.562 1.012 0"/>
|
||||
</symbol>
|
||||
<symbol id="x-icon" viewBox="0 0 19 19">
|
||||
<path fill="#08060d" fill-rule="evenodd" d="M1.893 1.98c.052.072 1.245 1.769 2.653 3.77l2.892 4.114c.183.261.333.48.333.486s-.068.089-.152.183l-.522.593-.765.867-3.597 4.087c-.375.426-.734.834-.798.905a1 1 0 0 0-.118.148c0 .01.236.017.664.017h.663l.729-.83c.4-.457.796-.906.879-.999a692 692 0 0 0 1.794-2.038c.034-.037.301-.34.594-.675l.551-.624.345-.392a7 7 0 0 1 .34-.374c.006 0 .93 1.306 2.052 2.903l2.084 2.965.045.063h2.275c1.87 0 2.273-.003 2.266-.021-.008-.02-1.098-1.572-3.894-5.547-2.013-2.862-2.28-3.246-2.273-3.266.008-.019.282-.332 2.085-2.38l2-2.274 1.567-1.782c.022-.028-.016-.03-.65-.03h-.674l-.3.342a871 871 0 0 1-1.782 2.025c-.067.075-.405.458-.75.852a100 100 0 0 1-.803.91c-.148.172-.299.344-.99 1.127-.304.343-.32.358-.345.327-.015-.019-.904-1.282-1.976-2.808L6.365 1.85H1.8zm1.782.91 8.078 11.294c.772 1.08 1.413 1.973 1.425 1.984.016.017.241.02 1.05.017l1.03-.004-2.694-3.766L7.796 5.75 5.722 2.852l-1.039-.004-1.039-.004z" clip-rule="evenodd"/>
|
||||
</symbol>
|
||||
</svg>
|
||||
|
After Width: | Height: | Size: 4.9 KiB |
@@ -0,0 +1,184 @@
|
||||
.counter {
|
||||
font-size: 16px;
|
||||
padding: 5px 10px;
|
||||
border-radius: 5px;
|
||||
color: var(--accent);
|
||||
background: var(--accent-bg);
|
||||
border: 2px solid transparent;
|
||||
transition: border-color 0.3s;
|
||||
margin-bottom: 24px;
|
||||
|
||||
&:hover {
|
||||
border-color: var(--accent-border);
|
||||
}
|
||||
&:focus-visible {
|
||||
outline: 2px solid var(--accent);
|
||||
outline-offset: 2px;
|
||||
}
|
||||
}
|
||||
|
||||
.hero {
|
||||
position: relative;
|
||||
|
||||
.base,
|
||||
.framework,
|
||||
.vite {
|
||||
inset-inline: 0;
|
||||
margin: 0 auto;
|
||||
}
|
||||
|
||||
.base {
|
||||
width: 170px;
|
||||
position: relative;
|
||||
z-index: 0;
|
||||
}
|
||||
|
||||
.framework,
|
||||
.vite {
|
||||
position: absolute;
|
||||
}
|
||||
|
||||
.framework {
|
||||
z-index: 1;
|
||||
top: 34px;
|
||||
height: 28px;
|
||||
transform: perspective(2000px) rotateZ(300deg) rotateX(44deg) rotateY(39deg)
|
||||
scale(1.4);
|
||||
}
|
||||
|
||||
.vite {
|
||||
z-index: 0;
|
||||
top: 107px;
|
||||
height: 26px;
|
||||
width: auto;
|
||||
transform: perspective(2000px) rotateZ(300deg) rotateX(40deg) rotateY(39deg)
|
||||
scale(0.8);
|
||||
}
|
||||
}
|
||||
|
||||
#center {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 25px;
|
||||
place-content: center;
|
||||
place-items: center;
|
||||
flex-grow: 1;
|
||||
|
||||
@media (max-width: 1024px) {
|
||||
padding: 32px 20px 24px;
|
||||
gap: 18px;
|
||||
}
|
||||
}
|
||||
|
||||
#next-steps {
|
||||
display: flex;
|
||||
border-top: 1px solid var(--border);
|
||||
text-align: left;
|
||||
|
||||
& > div {
|
||||
flex: 1 1 0;
|
||||
padding: 32px;
|
||||
@media (max-width: 1024px) {
|
||||
padding: 24px 20px;
|
||||
}
|
||||
}
|
||||
|
||||
.icon {
|
||||
margin-bottom: 16px;
|
||||
width: 22px;
|
||||
height: 22px;
|
||||
}
|
||||
|
||||
@media (max-width: 1024px) {
|
||||
flex-direction: column;
|
||||
text-align: center;
|
||||
}
|
||||
}
|
||||
|
||||
#docs {
|
||||
border-right: 1px solid var(--border);
|
||||
|
||||
@media (max-width: 1024px) {
|
||||
border-right: none;
|
||||
border-bottom: 1px solid var(--border);
|
||||
}
|
||||
}
|
||||
|
||||
#next-steps ul {
|
||||
list-style: none;
|
||||
padding: 0;
|
||||
display: flex;
|
||||
gap: 8px;
|
||||
margin: 32px 0 0;
|
||||
|
||||
.logo {
|
||||
height: 18px;
|
||||
}
|
||||
|
||||
a {
|
||||
color: var(--text-h);
|
||||
font-size: 16px;
|
||||
border-radius: 6px;
|
||||
background: var(--social-bg);
|
||||
display: flex;
|
||||
padding: 6px 12px;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
text-decoration: none;
|
||||
transition: box-shadow 0.3s;
|
||||
|
||||
&:hover {
|
||||
box-shadow: var(--shadow);
|
||||
}
|
||||
.button-icon {
|
||||
height: 18px;
|
||||
width: 18px;
|
||||
}
|
||||
}
|
||||
|
||||
@media (max-width: 1024px) {
|
||||
margin-top: 20px;
|
||||
flex-wrap: wrap;
|
||||
justify-content: center;
|
||||
|
||||
li {
|
||||
flex: 1 1 calc(50% - 8px);
|
||||
}
|
||||
|
||||
a {
|
||||
width: 100%;
|
||||
justify-content: center;
|
||||
box-sizing: border-box;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#spacer {
|
||||
height: 88px;
|
||||
border-top: 1px solid var(--border);
|
||||
@media (max-width: 1024px) {
|
||||
height: 48px;
|
||||
}
|
||||
}
|
||||
|
||||
.ticks {
|
||||
position: relative;
|
||||
width: 100%;
|
||||
|
||||
&::before,
|
||||
&::after {
|
||||
content: '';
|
||||
position: absolute;
|
||||
top: -4.5px;
|
||||
border: 5px solid transparent;
|
||||
}
|
||||
|
||||
&::before {
|
||||
left: 0;
|
||||
border-left-color: var(--border);
|
||||
}
|
||||
&::after {
|
||||
right: 0;
|
||||
border-right-color: var(--border);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
import { Routes, Route, Navigate } from 'react-router-dom'
|
||||
import { AuthProvider, useAuth } from './contexts/AuthContext'
|
||||
import Layout from './components/Layout'
|
||||
import Login from './pages/Login'
|
||||
import Register from './pages/Register'
|
||||
import Dashboard from './pages/Dashboard'
|
||||
import Users from './pages/Users'
|
||||
import Roles from './pages/Roles'
|
||||
import Modules from './pages/Modules'
|
||||
import ModuleView from './pages/ModuleView'
|
||||
|
||||
function ProtectedRoute({ children }: { children: React.ReactNode }) {
|
||||
const { user, loading } = useAuth()
|
||||
if (loading) return <div className="flex items-center justify-center h-screen">Загрузка...</div>
|
||||
if (!user) return <Navigate to="/login" />
|
||||
return <>{children}</>
|
||||
}
|
||||
|
||||
export default function App() {
|
||||
return (
|
||||
<AuthProvider>
|
||||
<Routes>
|
||||
<Route path="/login" element={<Login />} />
|
||||
<Route path="/register" element={<Register />} />
|
||||
<Route path="/" element={<ProtectedRoute><Layout /></ProtectedRoute>}>
|
||||
<Route index element={<Dashboard />} />
|
||||
<Route path="users" element={<Users />} />
|
||||
<Route path="roles" element={<Roles />} />
|
||||
<Route path="modules" element={<Modules />} />
|
||||
<Route path="module/:slug" element={<ModuleView />} />
|
||||
</Route>
|
||||
</Routes>
|
||||
</AuthProvider>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,58 @@
|
||||
import axios from 'axios'
|
||||
|
||||
const api = axios.create({ baseURL: '/api/v1' })
|
||||
|
||||
api.interceptors.request.use((config) => {
|
||||
const token = localStorage.getItem('platform_token')
|
||||
if (token) {
|
||||
config.headers.Authorization = `Bearer ${token}`
|
||||
}
|
||||
return config
|
||||
})
|
||||
|
||||
api.interceptors.response.use(
|
||||
(r) => r,
|
||||
(error) => {
|
||||
if (error.response?.status === 401) {
|
||||
localStorage.removeItem('platform_token')
|
||||
window.location.href = '/login'
|
||||
}
|
||||
return Promise.reject(error)
|
||||
}
|
||||
)
|
||||
|
||||
export const authApi = {
|
||||
login: (data: { email: string; password: string }) => api.post('/auth/login', data),
|
||||
register: (data: { email: string; password: string; first_name: string; last_name: string }) => api.post('/auth/register', data),
|
||||
me: () => api.get('/auth/me'),
|
||||
}
|
||||
|
||||
export const usersApi = {
|
||||
list: (params?: { page?: number; page_size?: number; search?: string }) => api.get('/users', { params }),
|
||||
get: (id: number) => api.get(`/users/${id}`),
|
||||
create: (data: { email: string; password: string; first_name: string; last_name: string; is_superadmin?: boolean; role_ids?: number[] }) => api.post('/users', data),
|
||||
update: (id: number, data: { email?: string; first_name?: string; last_name?: string; is_active?: boolean; is_superadmin?: boolean; password?: string }) => api.put(`/users/${id}`, data),
|
||||
delete: (id: number) => api.delete(`/users/${id}`),
|
||||
assignRole: (userId: number, roleId: number) => api.post(`/users/${userId}/roles/${roleId}`),
|
||||
removeRole: (userId: number, roleId: number) => api.delete(`/users/${userId}/roles/${roleId}`),
|
||||
assignModuleRole: (userId: number, moduleRoleId: number) => api.post(`/users/${userId}/module-roles/${moduleRoleId}`),
|
||||
removeModuleRole: (userId: number, moduleRoleId: number) => api.delete(`/users/${userId}/module-roles/${moduleRoleId}`),
|
||||
}
|
||||
|
||||
export const rolesApi = {
|
||||
list: () => api.get('/roles'),
|
||||
create: (data: { name: string; description?: string }) => api.post('/roles', data),
|
||||
update: (id: number, data: { name: string; description?: string }) => api.put(`/roles/${id}`, data),
|
||||
delete: (id: number) => api.delete(`/roles/${id}`),
|
||||
}
|
||||
|
||||
export const modulesApi = {
|
||||
list: () => api.get('/modules'),
|
||||
create: (data: { name: string; slug: string; url: string; description?: string; icon?: string }) => api.post('/modules', data),
|
||||
update: (id: number, data: any) => api.put(`/modules/${id}`, data),
|
||||
delete: (id: number) => api.delete(`/modules/${id}`),
|
||||
syncRoles: (id: number) => api.post(`/modules/${id}/sync-roles`),
|
||||
getRoles: (id: number) => api.get(`/modules/${id}/roles`),
|
||||
}
|
||||
|
||||
export default api
|
||||
|
After Width: | Height: | Size: 13 KiB |
@@ -0,0 +1 @@
|
||||
<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" aria-hidden="true" role="img" class="iconify iconify--logos" width="35.93" height="32" preserveAspectRatio="xMidYMid meet" viewBox="0 0 256 228"><path fill="#00D8FF" d="M210.483 73.824a171.49 171.49 0 0 0-8.24-2.597c.465-1.9.893-3.777 1.273-5.621c6.238-30.281 2.16-54.676-11.769-62.708c-13.355-7.7-35.196.329-57.254 19.526a171.23 171.23 0 0 0-6.375 5.848a155.866 155.866 0 0 0-4.241-3.917C100.759 3.829 77.587-4.822 63.673 3.233C50.33 10.957 46.379 33.89 51.995 62.588a170.974 170.974 0 0 0 1.892 8.48c-3.28.932-6.445 1.924-9.474 2.98C17.309 83.498 0 98.307 0 113.668c0 15.865 18.582 31.778 46.812 41.427a145.52 145.52 0 0 0 6.921 2.165a167.467 167.467 0 0 0-2.01 9.138c-5.354 28.2-1.173 50.591 12.134 58.266c13.744 7.926 36.812-.22 59.273-19.855a145.567 145.567 0 0 0 5.342-4.923a168.064 168.064 0 0 0 6.92 6.314c21.758 18.722 43.246 26.282 56.54 18.586c13.731-7.949 18.194-32.003 12.4-61.268a145.016 145.016 0 0 0-1.535-6.842c1.62-.48 3.21-.974 4.76-1.488c29.348-9.723 48.443-25.443 48.443-41.52c0-15.417-17.868-30.326-45.517-39.844Zm-6.365 70.984c-1.4.463-2.836.91-4.3 1.345c-3.24-10.257-7.612-21.163-12.963-32.432c5.106-11 9.31-21.767 12.459-31.957c2.619.758 5.16 1.557 7.61 2.4c23.69 8.156 38.14 20.213 38.14 29.504c0 9.896-15.606 22.743-40.946 31.14Zm-10.514 20.834c2.562 12.94 2.927 24.64 1.23 33.787c-1.524 8.219-4.59 13.698-8.382 15.893c-8.067 4.67-25.32-1.4-43.927-17.412a156.726 156.726 0 0 1-6.437-5.87c7.214-7.889 14.423-17.06 21.459-27.246c12.376-1.098 24.068-2.894 34.671-5.345a134.17 134.17 0 0 1 1.386 6.193ZM87.276 214.515c-7.882 2.783-14.16 2.863-17.955.675c-8.075-4.657-11.432-22.636-6.853-46.752a156.923 156.923 0 0 1 1.869-8.499c10.486 2.32 22.093 3.988 34.498 4.994c7.084 9.967 14.501 19.128 21.976 27.15a134.668 134.668 0 0 1-4.877 4.492c-9.933 8.682-19.886 14.842-28.658 17.94ZM50.35 144.747c-12.483-4.267-22.792-9.812-29.858-15.863c-6.35-5.437-9.555-10.836-9.555-15.216c0-9.322 13.897-21.212 37.076-29.293c2.813-.98 5.757-1.905 8.812-2.773c3.204 10.42 7.406 21.315 12.477 32.332c-5.137 11.18-9.399 22.249-12.634 32.792a134.718 134.718 0 0 1-6.318-1.979Zm12.378-84.26c-4.811-24.587-1.616-43.134 6.425-47.789c8.564-4.958 27.502 2.111 47.463 19.835a144.318 144.318 0 0 1 3.841 3.545c-7.438 7.987-14.787 17.08-21.808 26.988c-12.04 1.116-23.565 2.908-34.161 5.309a160.342 160.342 0 0 1-1.76-7.887Zm110.427 27.268a347.8 347.8 0 0 0-7.785-12.803c8.168 1.033 15.994 2.404 23.343 4.08c-2.206 7.072-4.956 14.465-8.193 22.045a381.151 381.151 0 0 0-7.365-13.322Zm-45.032-43.861c5.044 5.465 10.096 11.566 15.065 18.186a322.04 322.04 0 0 0-30.257-.006c4.974-6.559 10.069-12.652 15.192-18.18ZM82.802 87.83a323.167 323.167 0 0 0-7.227 13.238c-3.184-7.553-5.909-14.98-8.134-22.152c7.304-1.634 15.093-2.97 23.209-3.984a321.524 321.524 0 0 0-7.848 12.897Zm8.081 65.352c-8.385-.936-16.291-2.203-23.593-3.793c2.26-7.3 5.045-14.885 8.298-22.6a321.187 321.187 0 0 0 7.257 13.246c2.594 4.48 5.28 8.868 8.038 13.147Zm37.542 31.03c-5.184-5.592-10.354-11.779-15.403-18.433c4.902.192 9.899.29 14.978.29c5.218 0 10.376-.117 15.453-.343c-4.985 6.774-10.018 12.97-15.028 18.486Zm52.198-57.817c3.422 7.8 6.306 15.345 8.596 22.52c-7.422 1.694-15.436 3.058-23.88 4.071a382.417 382.417 0 0 0 7.859-13.026a347.403 347.403 0 0 0 7.425-13.565Zm-16.898 8.101a358.557 358.557 0 0 1-12.281 19.815a329.4 329.4 0 0 1-23.444.823c-7.967 0-15.716-.248-23.178-.732a310.202 310.202 0 0 1-12.513-19.846h.001a307.41 307.41 0 0 1-10.923-20.627a310.278 310.278 0 0 1 10.89-20.637l-.001.001a307.318 307.318 0 0 1 12.413-19.761c7.613-.576 15.42-.876 23.31-.876H128c7.926 0 15.743.303 23.354.883a329.357 329.357 0 0 1 12.335 19.695a358.489 358.489 0 0 1 11.036 20.54a329.472 329.472 0 0 1-11 20.722Zm22.56-122.124c8.572 4.944 11.906 24.881 6.52 51.026c-.344 1.668-.73 3.367-1.15 5.09c-10.622-2.452-22.155-4.275-34.23-5.408c-7.034-10.017-14.323-19.124-21.64-27.008a160.789 160.789 0 0 1 5.888-5.4c18.9-16.447 36.564-22.941 44.612-18.3ZM128 90.808c12.625 0 22.86 10.235 22.86 22.86s-10.235 22.86-22.86 22.86s-22.86-10.235-22.86-22.86s10.235-22.86 22.86-22.86Z"></path></svg>
|
||||
|
After Width: | Height: | Size: 4.0 KiB |
|
After Width: | Height: | Size: 8.5 KiB |
@@ -0,0 +1,85 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { Outlet, Link, useLocation, useNavigate } from 'react-router-dom'
|
||||
import { useAuth } from '../contexts/AuthContext'
|
||||
import { modulesApi } from '../api/client'
|
||||
import { Package, LogOut } from 'lucide-react'
|
||||
|
||||
export default function Layout() {
|
||||
const { user, logout } = useAuth()
|
||||
const location = useLocation()
|
||||
const navigate = useNavigate()
|
||||
const [modules, setModules] = useState<any[]>([])
|
||||
|
||||
const isAdmin = user?.is_superadmin || user?.roles?.includes('platform_admin')
|
||||
const isModuleView = location.pathname.startsWith('/module/')
|
||||
|
||||
useEffect(() => {
|
||||
modulesApi.list().then(res => setModules(res.data.filter((m: any) => m.is_active))).catch(() => {})
|
||||
}, [])
|
||||
|
||||
const handleLogout = () => { logout(); navigate('/login') }
|
||||
|
||||
return (
|
||||
<div className="flex flex-col h-screen bg-gray-100">
|
||||
{/* Top header */}
|
||||
<header className="bg-white shadow-sm flex-shrink-0">
|
||||
<div className="flex items-center justify-between h-12 px-4">
|
||||
{/* Left: logo + main nav */}
|
||||
<div className="flex items-center gap-6">
|
||||
<Link to="/" className="text-lg font-bold text-gray-800 whitespace-nowrap">Платформа</Link>
|
||||
<nav className="flex items-center gap-1">
|
||||
<Link to="/"
|
||||
className={`px-3 py-1.5 text-sm rounded-md transition-colors ${location.pathname === '/' ? 'bg-blue-50 text-blue-700 font-medium' : 'text-gray-600 hover:bg-gray-100'}`}>
|
||||
Панель
|
||||
</Link>
|
||||
{isAdmin && (
|
||||
<>
|
||||
<Link to="/users"
|
||||
className={`px-3 py-1.5 text-sm rounded-md transition-colors ${location.pathname.startsWith('/users') ? 'bg-blue-50 text-blue-700 font-medium' : 'text-gray-600 hover:bg-gray-100'}`}>
|
||||
Пользователи
|
||||
</Link>
|
||||
<Link to="/roles"
|
||||
className={`px-3 py-1.5 text-sm rounded-md transition-colors ${location.pathname.startsWith('/roles') ? 'bg-blue-50 text-blue-700 font-medium' : 'text-gray-600 hover:bg-gray-100'}`}>
|
||||
Роли
|
||||
</Link>
|
||||
<Link to="/modules"
|
||||
className={`px-3 py-1.5 text-sm rounded-md transition-colors ${location.pathname.startsWith('/modules') ? 'bg-blue-50 text-blue-700 font-medium' : 'text-gray-600 hover:bg-gray-100'}`}>
|
||||
Модули
|
||||
</Link>
|
||||
</>
|
||||
)}
|
||||
</nav>
|
||||
</div>
|
||||
|
||||
{/* Center: module tabs */}
|
||||
{modules.length > 0 && (
|
||||
<div className="flex items-center gap-1">
|
||||
{modules.map(mod => (
|
||||
<Link key={mod.slug} to={`/module/${mod.slug}`}
|
||||
className={`px-3 py-1.5 text-sm rounded-md transition-colors flex items-center gap-1.5 ${location.pathname === `/module/${mod.slug}` ? 'bg-blue-600 text-white font-medium' : 'text-gray-600 hover:bg-gray-100'}`}>
|
||||
<Package className="w-3.5 h-3.5" />{mod.name}
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Right: logout */}
|
||||
<button onClick={handleLogout} className="flex items-center gap-1.5 px-3 py-1.5 text-sm text-gray-600 hover:bg-gray-100 rounded-md">
|
||||
<LogOut className="w-4 h-4" />Выход
|
||||
</button>
|
||||
</div>
|
||||
</header>
|
||||
|
||||
{/* Content */}
|
||||
<div className="flex-1 flex flex-col min-w-0 overflow-hidden">
|
||||
{isModuleView ? (
|
||||
<Outlet />
|
||||
) : (
|
||||
<div className="flex-1 overflow-auto p-6">
|
||||
<Outlet />
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
import { createContext, useContext, useState, useEffect } from 'react'
|
||||
import type { ReactNode } from 'react'
|
||||
import { authApi } from '../api/client'
|
||||
|
||||
interface User {
|
||||
id: number
|
||||
email: string
|
||||
first_name: string
|
||||
last_name: string
|
||||
is_active: boolean
|
||||
is_superadmin: boolean
|
||||
roles: string[]
|
||||
module_roles: Record<string, string[]>
|
||||
}
|
||||
|
||||
interface AuthContextType {
|
||||
user: User | null
|
||||
loading: boolean
|
||||
login: (email: string, password: string) => Promise<void>
|
||||
logout: () => void
|
||||
}
|
||||
|
||||
const AuthContext = createContext<AuthContextType | undefined>(undefined)
|
||||
|
||||
export function AuthProvider({ children }: { children: ReactNode }) {
|
||||
const [user, setUser] = useState<User | null>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
|
||||
useEffect(() => {
|
||||
const token = localStorage.getItem('platform_token')
|
||||
if (token) {
|
||||
authApi.me()
|
||||
.then(res => setUser(res.data))
|
||||
.catch(() => localStorage.removeItem('platform_token'))
|
||||
.finally(() => setLoading(false))
|
||||
} else {
|
||||
setLoading(false)
|
||||
}
|
||||
}, [])
|
||||
|
||||
const login = async (email: string, password: string) => {
|
||||
const res = await authApi.login({ email, password })
|
||||
localStorage.setItem('platform_token', res.data.access_token)
|
||||
setUser(res.data.user)
|
||||
}
|
||||
|
||||
const logout = () => {
|
||||
localStorage.removeItem('platform_token')
|
||||
setUser(null)
|
||||
}
|
||||
|
||||
return (
|
||||
<AuthContext.Provider value={{ user, loading, login, logout }}>
|
||||
{children}
|
||||
</AuthContext.Provider>
|
||||
)
|
||||
}
|
||||
|
||||
export function useAuth() {
|
||||
const ctx = useContext(AuthContext)
|
||||
if (!ctx) throw new Error('useAuth must be inside AuthProvider')
|
||||
return ctx
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
@import "tailwindcss";
|
||||
@@ -0,0 +1,13 @@
|
||||
import { StrictMode } from 'react'
|
||||
import { createRoot } from 'react-dom/client'
|
||||
import { BrowserRouter } from 'react-router-dom'
|
||||
import App from './App'
|
||||
import './index.css'
|
||||
|
||||
createRoot(document.getElementById('root')!).render(
|
||||
<StrictMode>
|
||||
<BrowserRouter>
|
||||
<App />
|
||||
</BrowserRouter>
|
||||
</StrictMode>,
|
||||
)
|
||||
@@ -0,0 +1,42 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { usersApi, rolesApi, modulesApi } from '../api/client'
|
||||
import { Users, Key, Package } from 'lucide-react'
|
||||
|
||||
export default function Dashboard() {
|
||||
const [stats, setStats] = useState({ users: 0, roles: 0, modules: 0 })
|
||||
|
||||
useEffect(() => {
|
||||
Promise.all([
|
||||
usersApi.list({ page_size: 1 }).catch(() => ({ data: { total: 0 } })),
|
||||
rolesApi.list().catch(() => ({ data: [] })),
|
||||
modulesApi.list().catch(() => ({ data: [] })),
|
||||
]).then(([u, r, m]) => {
|
||||
setStats({ users: u.data.total, roles: r.data.length, modules: m.data.length })
|
||||
})
|
||||
}, [])
|
||||
|
||||
const cards = [
|
||||
{ name: 'Пользователи', value: stats.users, icon: Users, color: 'bg-blue-500' },
|
||||
{ name: 'Роли', value: stats.roles, icon: Key, color: 'bg-green-500' },
|
||||
{ name: 'Модули', value: stats.modules, icon: Package, color: 'bg-purple-500' },
|
||||
]
|
||||
|
||||
return (
|
||||
<div>
|
||||
<h1 className="text-2xl font-bold text-gray-900 mb-6">Панель управления</h1>
|
||||
<div className="grid grid-cols-1 md:grid-cols-3 gap-6">
|
||||
{cards.map(card => (
|
||||
<div key={card.name} className="bg-white rounded-lg shadow p-6 flex items-center gap-4">
|
||||
<div className={`${card.color} p-3 rounded-lg`}>
|
||||
<card.icon className="w-6 h-6 text-white" />
|
||||
</div>
|
||||
<div>
|
||||
<p className="text-sm text-gray-500">{card.name}</p>
|
||||
<p className="text-2xl font-bold text-gray-900">{card.value}</p>
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,59 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { useNavigate, Link } from 'react-router-dom'
|
||||
import { useAuth } from '../contexts/AuthContext'
|
||||
|
||||
export default function Login() {
|
||||
const [email, setEmail] = useState('')
|
||||
const [password, setPassword] = useState('')
|
||||
const [error, setError] = useState('')
|
||||
const [loading, setLoading] = useState(false)
|
||||
const { user, login } = useAuth()
|
||||
const navigate = useNavigate()
|
||||
|
||||
// If already logged in, redirect to home
|
||||
useEffect(() => {
|
||||
if (user) {
|
||||
navigate('/')
|
||||
}
|
||||
}, [user, navigate])
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
setError('')
|
||||
setLoading(true)
|
||||
try {
|
||||
await login(email, password)
|
||||
navigate('/')
|
||||
} catch (err: any) {
|
||||
setError(err.response?.data?.detail || 'Ошибка входа')
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-gray-100">
|
||||
<div className="bg-white p-8 rounded-lg shadow-md w-full max-w-md">
|
||||
<h1 className="text-2xl font-bold text-center mb-6">Платформа</h1>
|
||||
<h2 className="text-lg text-gray-600 text-center mb-8">Войдите в аккаунт</h2>
|
||||
{error && <div className="bg-red-50 text-red-600 p-3 rounded-lg mb-4 text-sm">{error}</div>}
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">Email</label>
|
||||
<input type="email" value={email} onChange={e => setEmail(e.target.value)} className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" required />
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">Пароль</label>
|
||||
<input type="password" value={password} onChange={e => setPassword(e.target.value)} className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" required />
|
||||
</div>
|
||||
<button type="submit" disabled={loading} className="w-full py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50">
|
||||
{loading ? 'Вход...' : 'Войти'}
|
||||
</button>
|
||||
</form>
|
||||
<p className="mt-4 text-center text-sm text-gray-600">
|
||||
Нет аккаунта? <Link to="/register" className="text-blue-600 hover:underline">Регистрация</Link>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,118 @@
|
||||
import { useState, useEffect, useRef } from 'react'
|
||||
import { useParams } from 'react-router-dom'
|
||||
import { modulesApi } from '../api/client'
|
||||
import { ExternalLink, Loader2 } from 'lucide-react'
|
||||
|
||||
export default function ModuleView() {
|
||||
const { slug } = useParams()
|
||||
const [module, setModule] = useState<any>(null)
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [iframeLoading, setIframeLoading] = useState(true)
|
||||
const [moduleUrl, setModuleUrl] = useState('')
|
||||
const iframeRef = useRef<HTMLIFrameElement>(null)
|
||||
|
||||
useEffect(() => {
|
||||
modulesApi.list().then(res => {
|
||||
const found = res.data.find((m: any) => m.slug === slug)
|
||||
setModule(found)
|
||||
}).finally(() => setLoading(false))
|
||||
}, [slug])
|
||||
|
||||
// Update iframe URL and send token to iframe
|
||||
useEffect(() => {
|
||||
if (!module) return
|
||||
|
||||
const getToken = () => localStorage.getItem('platform_token') || ''
|
||||
|
||||
const updateUrl = () => {
|
||||
const token = getToken()
|
||||
const url = `${module.url}?token=${encodeURIComponent(token)}`
|
||||
setModuleUrl(url)
|
||||
}
|
||||
|
||||
const sendTokenToIframe = () => {
|
||||
const token = getToken()
|
||||
const iframe = iframeRef.current
|
||||
if (iframe?.contentWindow) {
|
||||
iframe.contentWindow.postMessage(
|
||||
{ type: 'PLATFORM_TOKEN_UPDATE', token },
|
||||
module.url
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
updateUrl()
|
||||
|
||||
// Listen for storage changes (token refresh in another tab)
|
||||
const handleStorage = (e: StorageEvent) => {
|
||||
if (e.key === 'platform_token') {
|
||||
updateUrl()
|
||||
sendTokenToIframe()
|
||||
}
|
||||
}
|
||||
window.addEventListener('storage', handleStorage)
|
||||
|
||||
// Check periodically for token changes
|
||||
let lastToken = getToken()
|
||||
const interval = setInterval(() => {
|
||||
const currentToken = getToken()
|
||||
if (currentToken !== lastToken) {
|
||||
lastToken = currentToken
|
||||
updateUrl()
|
||||
sendTokenToIframe()
|
||||
}
|
||||
}, 10000)
|
||||
|
||||
return () => {
|
||||
window.removeEventListener('storage', handleStorage)
|
||||
clearInterval(interval)
|
||||
}
|
||||
}, [module])
|
||||
|
||||
useEffect(() => {
|
||||
setIframeLoading(true)
|
||||
}, [slug])
|
||||
|
||||
if (loading) return (
|
||||
<div className="flex-1 flex items-center justify-center">
|
||||
<Loader2 className="w-8 h-8 animate-spin text-blue-500" />
|
||||
</div>
|
||||
)
|
||||
|
||||
if (!module) return (
|
||||
<div className="flex-1 flex items-center justify-center">
|
||||
<p className="text-gray-500">Модуль не найден</p>
|
||||
</div>
|
||||
)
|
||||
|
||||
return (
|
||||
<div className="flex-1 flex flex-col h-full">
|
||||
<div className="flex items-center justify-between px-6 py-3 bg-white border-b flex-shrink-0">
|
||||
<h1 className="text-lg font-semibold text-gray-900">{module.name}</h1>
|
||||
<a href={moduleUrl} target="_blank" rel="noopener noreferrer"
|
||||
className="flex items-center gap-1 text-sm text-blue-600 hover:text-blue-800">
|
||||
<ExternalLink className="w-4 h-4" />Открыть отдельно
|
||||
</a>
|
||||
</div>
|
||||
<div className="flex-1 relative">
|
||||
{iframeLoading && (
|
||||
<div className="absolute inset-0 flex items-center justify-center bg-gray-50 z-10">
|
||||
<div className="text-center">
|
||||
<Loader2 className="w-8 h-8 animate-spin text-blue-500 mx-auto mb-2" />
|
||||
<p className="text-sm text-gray-500">Загрузка модуля...</p>
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
{moduleUrl && (
|
||||
<iframe
|
||||
ref={iframeRef}
|
||||
src={moduleUrl}
|
||||
className="w-full h-full border-0"
|
||||
title={module.name}
|
||||
onLoad={() => setIframeLoading(false)}
|
||||
/>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,147 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { modulesApi } from '../api/client'
|
||||
import { Plus, RefreshCw, Trash2, ExternalLink, Key } from 'lucide-react'
|
||||
|
||||
export default function Modules() {
|
||||
const [modules, setModules] = useState<any[]>([])
|
||||
const [showForm, setShowForm] = useState(false)
|
||||
const [form, setForm] = useState({ name: '', slug: '', url: '', description: '', icon: 'Package' })
|
||||
const [error, setError] = useState('')
|
||||
const [syncResult, setSyncResult] = useState('')
|
||||
const [expandedRoles, setExpandedRoles] = useState<number | null>(null)
|
||||
const [moduleRoles, setModuleRoles] = useState<any[]>([])
|
||||
|
||||
const fetchModules = () => { modulesApi.list().then(res => setModules(res.data)).catch(() => {}) }
|
||||
useEffect(() => { fetchModules() }, [])
|
||||
|
||||
const handleCreate = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
setError('')
|
||||
try {
|
||||
const res = await modulesApi.create(form)
|
||||
setForm({ name: '', slug: '', url: '', description: '', icon: 'Package' })
|
||||
setShowForm(false)
|
||||
fetchModules()
|
||||
alert(`Модуль создан. API Key: ${res.data.api_key}\nСохраните его — он нужен для настройки модуля.`)
|
||||
} catch (err: any) {
|
||||
setError(err.response?.data?.detail || 'Ошибка')
|
||||
}
|
||||
}
|
||||
|
||||
const handleSync = async (id: number) => {
|
||||
setSyncResult('')
|
||||
try {
|
||||
const res = await modulesApi.syncRoles(id)
|
||||
setSyncResult(`Импортировано: ${res.data.message}`)
|
||||
fetchModules()
|
||||
} catch (err: any) {
|
||||
setSyncResult(`Ошибка: ${err.response?.data?.detail || err.message}`)
|
||||
}
|
||||
}
|
||||
|
||||
const handleDelete = async (id: number) => {
|
||||
if (!confirm('Отключить модуль?')) return
|
||||
await modulesApi.delete(id)
|
||||
fetchModules()
|
||||
}
|
||||
|
||||
const toggleRoles = async (moduleId: number) => {
|
||||
if (expandedRoles === moduleId) {
|
||||
setExpandedRoles(null)
|
||||
setModuleRoles([])
|
||||
} else {
|
||||
setExpandedRoles(moduleId)
|
||||
modulesApi.getRoles(moduleId).then(res => setModuleRoles(res.data)).catch(() => {})
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="flex items-center justify-between mb-6">
|
||||
<h1 className="text-2xl font-bold text-gray-900">Модули</h1>
|
||||
<button onClick={() => setShowForm(!showForm)} className="flex items-center px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">
|
||||
<Plus className="w-4 h-4 mr-2" />Подключить
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{showForm && (
|
||||
<div className="bg-white rounded-lg shadow p-4 mb-6">
|
||||
<form onSubmit={handleCreate} className="space-y-4">
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">Название</label>
|
||||
<input type="text" value={form.name} onChange={e => setForm({...form, name: e.target.value})} required placeholder="Service Desk"
|
||||
className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">Slug</label>
|
||||
<input type="text" value={form.slug} onChange={e => setForm({...form, slug: e.target.value})} required placeholder="service-desk"
|
||||
className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" />
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">URL</label>
|
||||
<input type="text" value={form.url} onChange={e => setForm({...form, url: e.target.value})} required placeholder="http://localhost:8000"
|
||||
className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">Описание</label>
|
||||
<input type="text" value={form.description} onChange={e => setForm({...form, description: e.target.value})}
|
||||
className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" />
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<button type="submit" className="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700">Подключить</button>
|
||||
<button type="button" onClick={() => setShowForm(false)} className="px-4 py-2 border rounded-lg hover:bg-gray-100">Отмена</button>
|
||||
</div>
|
||||
{error && <p className="text-red-500 text-sm">{error}</p>}
|
||||
</form>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{syncResult && <div className="bg-blue-50 text-blue-800 p-3 rounded-lg mb-4 text-sm">{syncResult}</div>}
|
||||
|
||||
<div className="space-y-4">
|
||||
{modules.map(mod => (
|
||||
<div key={mod.id} className="bg-white rounded-lg shadow p-4">
|
||||
<div className="flex items-center justify-between">
|
||||
<div>
|
||||
<h3 className="font-semibold text-lg">{mod.name}</h3>
|
||||
<p className="text-sm text-gray-500">{mod.description}</p>
|
||||
<p className="text-xs text-gray-400 mt-1">{mod.url} · slug: {mod.slug} · ролей: {mod.roles_count}</p>
|
||||
</div>
|
||||
<div className="flex gap-2">
|
||||
<button onClick={() => toggleRoles(mod.id)} className="flex items-center gap-1 px-3 py-2 text-sm border rounded-lg hover:bg-gray-50" title="Роли">
|
||||
<Key className="w-4 h-4" />Роли
|
||||
</button>
|
||||
<button onClick={() => handleSync(mod.id)} className="flex items-center gap-1 px-3 py-2 text-sm border rounded-lg hover:bg-gray-50" title="Синхронизировать роли">
|
||||
<RefreshCw className="w-4 h-4" />Синхронизировать
|
||||
</button>
|
||||
<a href={mod.url} target="_blank" rel="noopener" className="flex items-center gap-1 px-3 py-2 text-sm border rounded-lg hover:bg-gray-50">
|
||||
<ExternalLink className="w-4 h-4" />Открыть
|
||||
</a>
|
||||
<button onClick={() => handleDelete(mod.id)} className="flex items-center px-3 py-2 text-sm border rounded-lg hover:bg-red-50 text-red-600">
|
||||
<Trash2 className="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
{expandedRoles === mod.id && (
|
||||
<div className="mt-4 pt-4 border-t">
|
||||
<h4 className="text-sm font-semibold mb-2">Роли модуля</h4>
|
||||
{moduleRoles.length === 0 ? (
|
||||
<p className="text-sm text-gray-500">Нет ролей. Нажмите "Синхронизировать".</p>
|
||||
) : (
|
||||
<div className="flex gap-2 flex-wrap">
|
||||
{moduleRoles.map(mr => (
|
||||
<span key={mr.id} className="px-3 py-1 text-sm bg-purple-100 text-purple-800 rounded-full">{mr.role_name}</span>
|
||||
))}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import { useState } from 'react'
|
||||
import { useNavigate, Link } from 'react-router-dom'
|
||||
import { authApi } from '../api/client'
|
||||
|
||||
export default function Register() {
|
||||
const [form, setForm] = useState({ email: '', password: '', first_name: '', last_name: '' })
|
||||
const [error, setError] = useState('')
|
||||
const [loading, setLoading] = useState(false)
|
||||
const navigate = useNavigate()
|
||||
|
||||
const handleSubmit = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
setError('')
|
||||
setLoading(true)
|
||||
try {
|
||||
await authApi.register(form)
|
||||
navigate('/login')
|
||||
} catch (err: any) {
|
||||
setError(err.response?.data?.detail || 'Ошибка регистрации')
|
||||
} finally {
|
||||
setLoading(false)
|
||||
}
|
||||
}
|
||||
|
||||
return (
|
||||
<div className="min-h-screen flex items-center justify-center bg-gray-100">
|
||||
<div className="bg-white p-8 rounded-lg shadow-md w-full max-w-md">
|
||||
<h1 className="text-2xl font-bold text-center mb-6">Платформа</h1>
|
||||
<h2 className="text-lg text-gray-600 text-center mb-8">Регистрация</h2>
|
||||
{error && <div className="bg-red-50 text-red-600 p-3 rounded-lg mb-4 text-sm">{error}</div>}
|
||||
<form onSubmit={handleSubmit} className="space-y-4">
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">Имя</label>
|
||||
<input type="text" value={form.first_name} onChange={e => setForm({...form, first_name: e.target.value})} className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" required />
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">Фамилия</label>
|
||||
<input type="text" value={form.last_name} onChange={e => setForm({...form, last_name: e.target.value})} className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" required />
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">Email</label>
|
||||
<input type="email" value={form.email} onChange={e => setForm({...form, email: e.target.value})} className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" required />
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">Пароль</label>
|
||||
<input type="password" value={form.password} onChange={e => setForm({...form, password: e.target.value})} className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" required minLength={6} />
|
||||
</div>
|
||||
<button type="submit" disabled={loading} className="w-full py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700 disabled:opacity-50">
|
||||
{loading ? 'Регистрация...' : 'Зарегистрироваться'}
|
||||
</button>
|
||||
</form>
|
||||
<p className="mt-4 text-center text-sm text-gray-600">
|
||||
Уже есть аккаунт? <Link to="/login" className="text-blue-600 hover:underline">Войти</Link>
|
||||
</p>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,98 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { rolesApi } from '../api/client'
|
||||
import { Plus, Trash2, Lock } from 'lucide-react'
|
||||
|
||||
export default function Roles() {
|
||||
const [roles, setRoles] = useState<any[]>([])
|
||||
const [showForm, setShowForm] = useState(false)
|
||||
const [form, setForm] = useState({ name: '', description: '' })
|
||||
const [error, setError] = useState('')
|
||||
|
||||
const fetchRoles = () => { rolesApi.list().then(res => setRoles(res.data)).catch(() => {}) }
|
||||
useEffect(() => { fetchRoles() }, [])
|
||||
|
||||
const handleCreate = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
setError('')
|
||||
try {
|
||||
await rolesApi.create(form)
|
||||
setForm({ name: '', description: '' })
|
||||
setShowForm(false)
|
||||
fetchRoles()
|
||||
} catch (err: any) {
|
||||
setError(err.response?.data?.detail || 'Ошибка')
|
||||
}
|
||||
}
|
||||
|
||||
const handleDelete = async (id: number, isSystem: boolean) => {
|
||||
if (isSystem) return
|
||||
if (!confirm('Удалить роль?')) return
|
||||
await rolesApi.delete(id)
|
||||
fetchRoles()
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="flex items-center justify-between mb-6">
|
||||
<h1 className="text-2xl font-bold text-gray-900">Глобальные роли</h1>
|
||||
<button onClick={() => setShowForm(!showForm)} className="flex items-center px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">
|
||||
<Plus className="w-4 h-4 mr-2" />Добавить
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{showForm && (
|
||||
<div className="bg-white rounded-lg shadow p-4 mb-6">
|
||||
<form onSubmit={handleCreate} className="flex gap-4 items-end">
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">Имя</label>
|
||||
<input type="text" value={form.name} onChange={e => setForm({...form, name: e.target.value})} required
|
||||
className="px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" />
|
||||
</div>
|
||||
<div className="flex-1">
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">Описание</label>
|
||||
<input type="text" value={form.description} onChange={e => setForm({...form, description: e.target.value})}
|
||||
className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" />
|
||||
</div>
|
||||
<button type="submit" className="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700">Создать</button>
|
||||
</form>
|
||||
{error && <p className="text-red-500 text-sm mt-2">{error}</p>}
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="bg-white rounded-lg shadow overflow-hidden">
|
||||
<table className="w-full">
|
||||
<thead className="bg-gray-50">
|
||||
<tr>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Имя</th>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Описание</th>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Тип</th>
|
||||
<th className="px-6 py-3 text-left text-xs font-medium text-gray-500 uppercase">Действия</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-gray-200">
|
||||
{roles.map(r => (
|
||||
<tr key={r.id} className="hover:bg-gray-50">
|
||||
<td className="px-6 py-4 text-sm font-medium">{r.name}</td>
|
||||
<td className="px-6 py-4 text-sm text-gray-500">{r.description || '-'}</td>
|
||||
<td className="px-6 py-4">
|
||||
{r.is_system ? (
|
||||
<span className="flex items-center gap-1 text-xs text-gray-500"><Lock className="w-3 h-3" /> Системная</span>
|
||||
) : (
|
||||
<span className="text-xs text-blue-600">Пользовательская</span>
|
||||
)}
|
||||
</td>
|
||||
<td className="px-6 py-4">
|
||||
{!r.is_system && (
|
||||
<button onClick={() => handleDelete(r.id, r.is_system)} className="text-red-500 hover:text-red-700">
|
||||
<Trash2 className="w-4 h-4" />
|
||||
</button>
|
||||
)}
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,341 @@
|
||||
import { useState, useEffect } from 'react'
|
||||
import { usersApi, rolesApi, modulesApi } from '../api/client'
|
||||
import { Search, Shield, Package, Plus, Edit, Trash2, X } from 'lucide-react'
|
||||
|
||||
export default function Users() {
|
||||
const [users, setUsers] = useState<any[]>([])
|
||||
const [roles, setRoles] = useState<any[]>([])
|
||||
const [modules, setModules] = useState<any[]>([])
|
||||
const [moduleRoles, setModuleRoles] = useState<any[]>([])
|
||||
const [loading, setLoading] = useState(true)
|
||||
const [search, setSearch] = useState('')
|
||||
const [page, setPage] = useState(1)
|
||||
const [total, setTotal] = useState(0)
|
||||
const [selectedUser, setSelectedUser] = useState<any>(null)
|
||||
const [showCreateForm, setShowCreateForm] = useState(false)
|
||||
const [showEditForm, setShowEditForm] = useState(false)
|
||||
const [editForm, setEditForm] = useState({ first_name: '', last_name: '', email: '', password: '', is_active: true, is_superadmin: false })
|
||||
const [createForm, setCreateForm] = useState({ email: '', password: '', first_name: '', last_name: '', is_superadmin: false })
|
||||
const [error, setError] = useState('')
|
||||
const pageSize = 20
|
||||
|
||||
const fetchUsers = () => {
|
||||
setLoading(true)
|
||||
usersApi.list({ page, page_size: pageSize, search: search || undefined })
|
||||
.then(res => { setUsers(res.data.users); setTotal(res.data.total) })
|
||||
.finally(() => setLoading(false))
|
||||
}
|
||||
|
||||
useEffect(() => { fetchUsers() }, [page])
|
||||
useEffect(() => {
|
||||
rolesApi.list().then(res => setRoles(res.data)).catch(() => {})
|
||||
modulesApi.list().then(res => setModules(res.data)).catch(() => {})
|
||||
}, [])
|
||||
|
||||
const loadModuleRoles = (moduleId: number) => {
|
||||
modulesApi.getRoles(moduleId).then(res => setModuleRoles(res.data)).catch(() => {})
|
||||
}
|
||||
|
||||
const handleAssignRole = async (userId: number, roleId: number) => {
|
||||
await usersApi.assignRole(userId, roleId)
|
||||
fetchUsers()
|
||||
if (selectedUser?.id === userId) {
|
||||
const res = await usersApi.get(userId)
|
||||
setSelectedUser(res.data)
|
||||
}
|
||||
}
|
||||
|
||||
const handleRemoveRole = async (userId: number, roleId: number) => {
|
||||
await usersApi.removeRole(userId, roleId)
|
||||
fetchUsers()
|
||||
if (selectedUser?.id === userId) {
|
||||
const res = await usersApi.get(userId)
|
||||
setSelectedUser(res.data)
|
||||
}
|
||||
}
|
||||
|
||||
const handleAssignModuleRole = async (userId: number, moduleRoleId: number) => {
|
||||
await usersApi.assignModuleRole(userId, moduleRoleId)
|
||||
fetchUsers()
|
||||
if (selectedUser?.id === userId) {
|
||||
const res = await usersApi.get(userId)
|
||||
setSelectedUser(res.data)
|
||||
}
|
||||
}
|
||||
|
||||
const handleCreate = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
setError('')
|
||||
try {
|
||||
await usersApi.create(createForm)
|
||||
setCreateForm({ email: '', password: '', first_name: '', last_name: '', is_superadmin: false })
|
||||
setShowCreateForm(false)
|
||||
fetchUsers()
|
||||
} catch (err: any) {
|
||||
setError(err.response?.data?.detail || 'Ошибка создания')
|
||||
}
|
||||
}
|
||||
|
||||
const handleEdit = async (e: React.FormEvent) => {
|
||||
e.preventDefault()
|
||||
if (!selectedUser) return
|
||||
setError('')
|
||||
try {
|
||||
const data: any = { ...editForm }
|
||||
if (!data.password) delete data.password
|
||||
await usersApi.update(selectedUser.id, data)
|
||||
setShowEditForm(false)
|
||||
fetchUsers()
|
||||
const res = await usersApi.get(selectedUser.id)
|
||||
setSelectedUser(res.data)
|
||||
} catch (err: any) {
|
||||
setError(err.response?.data?.detail || 'Ошибка обновления')
|
||||
}
|
||||
}
|
||||
|
||||
const handleDelete = async (userId: number) => {
|
||||
if (!confirm('Удалить пользователя? Это действие нельзя отменить.')) return
|
||||
await usersApi.delete(userId)
|
||||
fetchUsers()
|
||||
if (selectedUser?.id === userId) {
|
||||
setSelectedUser(null)
|
||||
}
|
||||
}
|
||||
|
||||
const openEditForm = (user: any) => {
|
||||
setEditForm({
|
||||
first_name: user.first_name,
|
||||
last_name: user.last_name,
|
||||
email: user.email,
|
||||
password: '',
|
||||
is_active: user.is_active,
|
||||
is_superadmin: user.is_superadmin,
|
||||
})
|
||||
setShowEditForm(true)
|
||||
setError('')
|
||||
}
|
||||
|
||||
return (
|
||||
<div>
|
||||
<div className="flex items-center justify-between mb-6">
|
||||
<h1 className="text-2xl font-bold text-gray-900">Пользователи</h1>
|
||||
<button onClick={() => { setShowCreateForm(true); setError('') }} className="flex items-center px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">
|
||||
<Plus className="w-4 h-4 mr-2" />Добавить
|
||||
</button>
|
||||
</div>
|
||||
|
||||
{/* Create form */}
|
||||
{showCreateForm && (
|
||||
<div className="bg-white rounded-lg shadow p-4 mb-6">
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<h3 className="font-semibold">Новый пользователь</h3>
|
||||
<button onClick={() => setShowCreateForm(false)}><X className="w-5 h-5 text-gray-400" /></button>
|
||||
</div>
|
||||
<form onSubmit={handleCreate} className="space-y-4">
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">Имя</label>
|
||||
<input type="text" value={createForm.first_name} onChange={e => setCreateForm({...createForm, first_name: e.target.value})} required
|
||||
className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">Фамилия</label>
|
||||
<input type="text" value={createForm.last_name} onChange={e => setCreateForm({...createForm, last_name: e.target.value})} required
|
||||
className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" />
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">Email</label>
|
||||
<input type="email" value={createForm.email} onChange={e => setCreateForm({...createForm, email: e.target.value})} required
|
||||
className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">Пароль</label>
|
||||
<input type="password" value={createForm.password} onChange={e => setCreateForm({...createForm, password: e.target.value})} required minLength={6}
|
||||
className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" />
|
||||
</div>
|
||||
<label className="flex items-center gap-2">
|
||||
<input type="checkbox" checked={createForm.is_superadmin} onChange={e => setCreateForm({...createForm, is_superadmin: e.target.checked})} className="rounded" />
|
||||
<span className="text-sm text-gray-700">Суперадминистратор</span>
|
||||
</label>
|
||||
{error && <p className="text-red-500 text-sm">{error}</p>}
|
||||
<div className="flex gap-2">
|
||||
<button type="submit" className="px-4 py-2 bg-green-600 text-white rounded-lg hover:bg-green-700">Создать</button>
|
||||
<button type="button" onClick={() => setShowCreateForm(false)} className="px-4 py-2 border rounded-lg hover:bg-gray-100">Отмена</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
)}
|
||||
|
||||
{/* Edit form */}
|
||||
{showEditForm && selectedUser && (
|
||||
<div className="bg-white rounded-lg shadow p-4 mb-6">
|
||||
<div className="flex items-center justify-between mb-4">
|
||||
<h3 className="font-semibold">Редактирование: {selectedUser.first_name} {selectedUser.last_name}</h3>
|
||||
<button onClick={() => setShowEditForm(false)}><X className="w-5 h-5 text-gray-400" /></button>
|
||||
</div>
|
||||
<form onSubmit={handleEdit} className="space-y-4">
|
||||
<div className="grid grid-cols-2 gap-4">
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">Имя</label>
|
||||
<input type="text" value={editForm.first_name} onChange={e => setEditForm({...editForm, first_name: e.target.value})} required
|
||||
className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">Фамилия</label>
|
||||
<input type="text" value={editForm.last_name} onChange={e => setEditForm({...editForm, last_name: e.target.value})} required
|
||||
className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" />
|
||||
</div>
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">Email</label>
|
||||
<input type="email" value={editForm.email} onChange={e => setEditForm({...editForm, email: e.target.value})} required
|
||||
className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" />
|
||||
</div>
|
||||
<div>
|
||||
<label className="block text-sm font-medium text-gray-700 mb-1">Новый пароль (оставьте пустым, чтобы не менять)</label>
|
||||
<input type="password" value={editForm.password} onChange={e => setEditForm({...editForm, password: e.target.value})} minLength={6}
|
||||
className="w-full px-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" />
|
||||
</div>
|
||||
<div className="flex gap-4">
|
||||
<label className="flex items-center gap-2">
|
||||
<input type="checkbox" checked={editForm.is_active} onChange={e => setEditForm({...editForm, is_active: e.target.checked})} className="rounded" />
|
||||
<span className="text-sm text-gray-700">Активен</span>
|
||||
</label>
|
||||
<label className="flex items-center gap-2">
|
||||
<input type="checkbox" checked={editForm.is_superadmin} onChange={e => setEditForm({...editForm, is_superadmin: e.target.checked})} className="rounded" />
|
||||
<span className="text-sm text-gray-700">Суперадминистратор</span>
|
||||
</label>
|
||||
</div>
|
||||
{error && <p className="text-red-500 text-sm">{error}</p>}
|
||||
<div className="flex gap-2">
|
||||
<button type="submit" className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">Сохранить</button>
|
||||
<button type="button" onClick={() => setShowEditForm(false)} className="px-4 py-2 border rounded-lg hover:bg-gray-100">Отмена</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
)}
|
||||
|
||||
<div className="bg-white rounded-lg shadow p-4 mb-6">
|
||||
<form onSubmit={e => { e.preventDefault(); setPage(1); fetchUsers() }} className="flex gap-4">
|
||||
<div className="flex-1 relative">
|
||||
<Search className="absolute left-3 top-2.5 w-4 h-4 text-gray-400" />
|
||||
<input type="text" value={search} onChange={e => setSearch(e.target.value)} placeholder="Поиск..."
|
||||
className="w-full pl-10 pr-3 py-2 border rounded-lg focus:outline-none focus:ring-2 focus:ring-blue-500" />
|
||||
</div>
|
||||
<button type="submit" className="px-4 py-2 bg-blue-600 text-white rounded-lg hover:bg-blue-700">Найти</button>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<div className="grid grid-cols-1 lg:grid-cols-3 gap-6">
|
||||
<div className="lg:col-span-2 bg-white rounded-lg shadow overflow-hidden">
|
||||
{loading ? <div className="p-8 text-center">Загрузка...</div> : (
|
||||
<table className="w-full">
|
||||
<thead className="bg-gray-50">
|
||||
<tr>
|
||||
<th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Пользователь</th>
|
||||
<th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Роли</th>
|
||||
<th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Статус</th>
|
||||
<th className="px-4 py-3 text-left text-xs font-medium text-gray-500 uppercase">Действия</th>
|
||||
</tr>
|
||||
</thead>
|
||||
<tbody className="divide-y divide-gray-200">
|
||||
{users.map(u => (
|
||||
<tr key={u.id} className="hover:bg-gray-50 cursor-pointer" onClick={() => setSelectedUser(u)}>
|
||||
<td className="px-4 py-3">
|
||||
<p className="text-sm font-medium">{u.first_name} {u.last_name}</p>
|
||||
<p className="text-xs text-gray-500">{u.email}</p>
|
||||
</td>
|
||||
<td className="px-4 py-3">
|
||||
<div className="flex gap-1 flex-wrap">
|
||||
{u.roles?.map((r: string) => <span key={r} className="px-2 py-0.5 text-xs bg-blue-100 text-blue-800 rounded-full">{r}</span>)}
|
||||
</div>
|
||||
</td>
|
||||
<td className="px-4 py-3">
|
||||
<span className={`px-2 py-1 text-xs rounded-full ${u.is_active ? 'bg-green-100 text-green-800' : 'bg-red-100 text-red-800'}`}>
|
||||
{u.is_active ? 'Активен' : 'Неактивен'}
|
||||
</span>
|
||||
</td>
|
||||
<td className="px-4 py-3" onClick={e => e.stopPropagation()}>
|
||||
<div className="flex gap-1">
|
||||
<button onClick={() => { setSelectedUser(u); openEditForm(u) }} className="p-1 text-blue-500 hover:text-blue-700" title="Редактировать">
|
||||
<Edit className="w-4 h-4" />
|
||||
</button>
|
||||
<button onClick={() => handleDelete(u.id)} className="p-1 text-red-500 hover:text-red-700" title="Удалить">
|
||||
<Trash2 className="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
</td>
|
||||
</tr>
|
||||
))}
|
||||
</tbody>
|
||||
</table>
|
||||
)}
|
||||
{total > pageSize && (
|
||||
<div className="px-4 py-3 border-t flex justify-between">
|
||||
<button onClick={() => setPage(p => Math.max(1, p - 1))} disabled={page === 1} className="px-3 py-1 border rounded disabled:opacity-50">Назад</button>
|
||||
<span className="text-sm text-gray-500">Страница {page}</span>
|
||||
<button onClick={() => setPage(p => p + 1)} disabled={page * pageSize >= total} className="px-3 py-1 border rounded disabled:opacity-50">Далее</button>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
|
||||
{selectedUser && !showEditForm && (
|
||||
<div className="bg-white rounded-lg shadow p-4">
|
||||
<div className="flex items-center justify-between mb-2">
|
||||
<h3 className="font-semibold text-lg">{selectedUser.first_name} {selectedUser.last_name}</h3>
|
||||
<button onClick={() => openEditForm(selectedUser)} className="text-blue-500 hover:text-blue-700">
|
||||
<Edit className="w-4 h-4" />
|
||||
</button>
|
||||
</div>
|
||||
<p className="text-sm text-gray-500 mb-4">{selectedUser.email}</p>
|
||||
|
||||
<div className="mb-4">
|
||||
<h4 className="text-sm font-semibold text-gray-700 mb-2 flex items-center gap-1"><Shield className="w-4 h-4" /> Глобальные роли</h4>
|
||||
<div className="space-y-1">
|
||||
{roles.map(r => {
|
||||
const assigned = selectedUser.roles?.includes(r.name)
|
||||
return (
|
||||
<div key={r.id} className="flex items-center justify-between text-sm">
|
||||
<span>{r.name}</span>
|
||||
{assigned ? (
|
||||
<button onClick={() => handleRemoveRole(selectedUser.id, r.id)} className="text-red-500 hover:text-red-700 text-xs">Убрать</button>
|
||||
) : (
|
||||
<button onClick={() => handleAssignRole(selectedUser.id, r.id)} className="text-blue-500 hover:text-blue-700 text-xs">Назначить</button>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<div>
|
||||
<h4 className="text-sm font-semibold text-gray-700 mb-2 flex items-center gap-1"><Package className="w-4 h-4" /> Роли модулей</h4>
|
||||
{modules.map(mod => (
|
||||
<div key={mod.id} className="mb-2">
|
||||
<p className="text-xs font-medium text-gray-600">{mod.name}</p>
|
||||
<button onClick={() => loadModuleRoles(mod.id)} className="text-xs text-blue-500 hover:text-blue-700">Загрузить роли</button>
|
||||
<div className="mt-1 space-y-1">
|
||||
{moduleRoles.filter(mr => mr.module_id === mod.id).map(mr => {
|
||||
const assigned = selectedUser.module_roles?.[mod.slug]?.includes(mr.role_name)
|
||||
return (
|
||||
<div key={mr.id} className="flex items-center justify-between text-xs pl-2">
|
||||
<span>{mr.role_name}</span>
|
||||
{assigned ? (
|
||||
<button onClick={() => usersApi.removeModuleRole(selectedUser.id, mr.id).then(() => { usersApi.get(selectedUser.id).then(r => setSelectedUser(r.data)); fetchUsers() })} className="text-red-500">Убрать</button>
|
||||
) : (
|
||||
<button onClick={() => handleAssignModuleRole(selectedUser.id, mr.id)} className="text-blue-500">Назначить</button>
|
||||
)}
|
||||
</div>
|
||||
)
|
||||
})}
|
||||
</div>
|
||||
</div>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.app.tsbuildinfo",
|
||||
"target": "es2023",
|
||||
"lib": ["ES2023", "DOM"],
|
||||
"module": "esnext",
|
||||
"types": ["vite/client"],
|
||||
"allowArbitraryExtensions": true,
|
||||
"skipLibCheck": true,
|
||||
|
||||
/* Bundler mode */
|
||||
"moduleResolution": "bundler",
|
||||
"allowImportingTsExtensions": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
"jsx": "react-jsx",
|
||||
|
||||
/* Linting */
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"erasableSyntaxOnly": true,
|
||||
"noFallthroughCasesInSwitch": true
|
||||
},
|
||||
"include": ["src"]
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"files": [],
|
||||
"references": [
|
||||
{ "path": "./tsconfig.app.json" },
|
||||
{ "path": "./tsconfig.node.json" }
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"compilerOptions": {
|
||||
"tsBuildInfoFile": "./node_modules/.tmp/tsconfig.node.tsbuildinfo",
|
||||
"target": "es2023",
|
||||
"lib": ["ES2023"],
|
||||
"types": ["node"],
|
||||
"skipLibCheck": true,
|
||||
|
||||
/* Bundler mode */
|
||||
"module": "nodenext",
|
||||
"allowImportingTsExtensions": true,
|
||||
"verbatimModuleSyntax": true,
|
||||
"moduleDetection": "force",
|
||||
"noEmit": true,
|
||||
|
||||
/* Linting */
|
||||
"noUnusedLocals": true,
|
||||
"noUnusedParameters": true,
|
||||
"erasableSyntaxOnly": true,
|
||||
"noFallthroughCasesInSwitch": true
|
||||
},
|
||||
"include": ["vite.config.ts"]
|
||||
}
|
||||
@@ -0,0 +1,13 @@
|
||||
import { defineConfig } from 'vite'
|
||||
import react from '@vitejs/plugin-react'
|
||||
import tailwindcss from '@tailwindcss/vite'
|
||||
|
||||
export default defineConfig({
|
||||
plugins: [react(), tailwindcss()],
|
||||
server: {
|
||||
port: 5173,
|
||||
proxy: {
|
||||
'/api': 'http://localhost:8001',
|
||||
},
|
||||
},
|
||||
})
|
||||
@@ -0,0 +1,43 @@
|
||||
# Environment Configuration
|
||||
|
||||
# Application
|
||||
APP_ENV=development
|
||||
APP_DEBUG=True
|
||||
APP_NAME=Service Request System
|
||||
APP_VERSION=1.0.0
|
||||
APP_CORS_ORIGINS=http://localhost:3000,http://localhost:5173
|
||||
|
||||
# Database
|
||||
DATABASE_URL=postgresql://user:password@localhost:5432/service_request
|
||||
|
||||
# Redis
|
||||
REDIS_URL=redis://localhost:6379/0
|
||||
|
||||
# RabbitMQ
|
||||
RABBITMQ_URL=amqp://guest:guest@localhost:5672/
|
||||
|
||||
# JWT
|
||||
JWT_SECRET_KEY=your-secret-key-here-change-in-production
|
||||
JWT_ALGORITHM=HS256
|
||||
JWT_ACCESS_TOKEN_EXPIRE_MINUTES=30
|
||||
|
||||
# Email
|
||||
SMTP_SERVER=smtp.gmail.com
|
||||
SMTP_PORT=465
|
||||
SMTP_USERNAME=your-email@gmail.com
|
||||
SMTP_PASSWORD=your-app-password
|
||||
EMAIL_FROM=your-email@gmail.com
|
||||
|
||||
# SMS
|
||||
TWILIO_ACCOUNT_SID=your-twilio-account-sid
|
||||
TWILIO_AUTH_TOKEN=your-twilio-auth-token
|
||||
TWILIO_FROM_NUMBER=+15017250604
|
||||
|
||||
# Migration
|
||||
MANAGEENGINE_CONNECTION_STRING=DRIVER={ODBC Driver 17 for SQL Server};SERVER=manageengine_server;DATABASE=ManageEngineSDP;UID=admin;PWD=password
|
||||
|
||||
# Platform integration
|
||||
PLATFORM_API_URL=http://platform:8000
|
||||
PLATFORM_API_KEY=your-platform-api-key
|
||||
PLATFORM_JWT_PUBLIC_KEY=your-rsa-public-key
|
||||
PLATFORM_JWT_ALGORITHM=RS256
|
||||
@@ -0,0 +1,63 @@
|
||||
# Python
|
||||
__pycache__/
|
||||
*.py[cod]
|
||||
*$py.class
|
||||
*.so
|
||||
.Python
|
||||
build/
|
||||
develop-eggs/
|
||||
dist/
|
||||
downloads/
|
||||
eggs/
|
||||
.eggs/
|
||||
lib/
|
||||
lib64/
|
||||
parts/
|
||||
sdist/
|
||||
var/
|
||||
wheels/
|
||||
*.egg-info/
|
||||
.installed.cfg
|
||||
*.egg
|
||||
|
||||
# Virtual Environment
|
||||
venv/
|
||||
ENV/
|
||||
env/
|
||||
.venv
|
||||
|
||||
# Environment Variables
|
||||
.env
|
||||
.env.local
|
||||
|
||||
# Database
|
||||
*.db
|
||||
*.sqlite
|
||||
*.sqlite3
|
||||
|
||||
# IDE
|
||||
.vscode/
|
||||
.idea/
|
||||
*.swp
|
||||
*.swo
|
||||
*~
|
||||
|
||||
# OS
|
||||
.DS_Store
|
||||
Thumbs.db
|
||||
|
||||
# Testing
|
||||
.pytest_cache/
|
||||
.coverage
|
||||
htmlcov/
|
||||
.tox/
|
||||
|
||||
# Logs
|
||||
*.log
|
||||
logs/
|
||||
|
||||
# Migrations
|
||||
migrations/alembic/versions/*.pyc
|
||||
|
||||
# Docker
|
||||
.dockerignore
|
||||
@@ -0,0 +1,32 @@
|
||||
FROM python:3.11-slim
|
||||
|
||||
WORKDIR /app
|
||||
|
||||
# Install system dependencies
|
||||
RUN apt-get update && apt-get install -y \
|
||||
gcc \
|
||||
postgresql-client \
|
||||
&& rm -rf /var/lib/apt/lists/*
|
||||
|
||||
# Copy requirements first for better caching
|
||||
COPY requirements.txt .
|
||||
|
||||
# Install Python dependencies
|
||||
RUN pip install --no-cache-dir -r requirements.txt
|
||||
|
||||
# Copy application code
|
||||
COPY . .
|
||||
|
||||
# Create non-root user
|
||||
RUN useradd -m -u 1001 appuser
|
||||
USER appuser
|
||||
|
||||
# Set environment variables
|
||||
ENV PYTHONUNBUFFERED=1
|
||||
ENV PYTHONDONTWRITEBYTECODE=1
|
||||
|
||||
# Expose port
|
||||
EXPOSE 8000
|
||||
|
||||
# Command to run application
|
||||
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
|
||||
@@ -0,0 +1,291 @@
|
||||
# Service Request System - Quick Start Guide
|
||||
|
||||
## 1. Настройка окружения
|
||||
|
||||
```bash
|
||||
# 1. Склонировать проект
|
||||
cd service-request-system
|
||||
|
||||
# 2. Скопировать .env.example в .env
|
||||
cp .env.example .env
|
||||
|
||||
# 3. Отредактировать .env и заполнить параметры:
|
||||
# - DATABASE_URL (PostgreSQL)
|
||||
# - SMTP credentials
|
||||
# - JWT_SECRET_KEY
|
||||
# - TWILIO credentials (если используется SMS)
|
||||
```
|
||||
|
||||
## 2. Запуск через Docker Compose
|
||||
|
||||
```bash
|
||||
# Запуск всех сервисов
|
||||
docker-compose up -d
|
||||
|
||||
# Проверка статуса
|
||||
docker-compose ps
|
||||
|
||||
# Просмотр логов
|
||||
docker-compose logs -f app
|
||||
```
|
||||
|
||||
После запуска сервисы будут доступны по:
|
||||
- **API**: http://localhost:8000
|
||||
- **Swagger UI**: http://localhost:8000/docs
|
||||
- **RabbitMQ Management**: http://localhost:15672 (guest/guest)
|
||||
|
||||
## 3. Создание суперпользователя
|
||||
|
||||
```bash
|
||||
docker-compose exec app python -c "
|
||||
from app.core.database import init_db, SessionLocal
|
||||
from app.core.security import get_password_hash
|
||||
from app.models.user import User
|
||||
from app.models.role import Role
|
||||
from app.models.extra import UserRole
|
||||
|
||||
init_db()
|
||||
db = SessionLocal()
|
||||
|
||||
# Create admin role if not exists
|
||||
admin_role = db.query(Role).filter(Role.name == 'admin').first()
|
||||
if not admin_role:
|
||||
admin_role = Role(name='admin', description='Administrator')
|
||||
db.add(admin_role)
|
||||
db.commit()
|
||||
db.refresh(admin_role)
|
||||
|
||||
# Create admin user
|
||||
user = User(
|
||||
email='admin@example.com',
|
||||
password_hash=get_password_hash('admin123'),
|
||||
first_name='Admin',
|
||||
last_name='User',
|
||||
is_active=True
|
||||
)
|
||||
db.add(user)
|
||||
db.commit()
|
||||
db.refresh(user)
|
||||
|
||||
# Assign admin role
|
||||
user_role = UserRole(user_id=user.id, role_id=admin_role.id)
|
||||
db.add(user_role)
|
||||
db.commit()
|
||||
|
||||
print(f'Admin created: {user.email}')
|
||||
"
|
||||
```
|
||||
|
||||
## 4. Регистрация пользователей
|
||||
|
||||
```bash
|
||||
# Зарегистрировать нового пользователя
|
||||
curl -X POST http://localhost:8000/api/v1/auth/register \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"email": "user@example.com",
|
||||
"password": "password123",
|
||||
"first_name": "John",
|
||||
"last_name": "Doe"
|
||||
}'
|
||||
```
|
||||
|
||||
## 5. Вход в систему
|
||||
|
||||
```bash
|
||||
# Войти и получить токен
|
||||
curl -X POST http://localhost:8000/api/v1/auth/login \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"email": "user@example.com",
|
||||
"password": "password123"
|
||||
}'
|
||||
|
||||
# Ответ будет содержать access_token
|
||||
```
|
||||
|
||||
## 6. Создание тикета
|
||||
|
||||
```bash
|
||||
# Использовать токен из предыдущего шага
|
||||
TOKEN=<access_token>
|
||||
|
||||
curl -X POST http://localhost:8000/api/v1/tickets \
|
||||
-H "Content-Type: application/json" \
|
||||
-H "Authorization: Bearer $TOKEN" \
|
||||
-d '{
|
||||
"subject": "Test Ticket",
|
||||
"description": "This is a test ticket",
|
||||
"category_id": 1,
|
||||
"priority_id": 2,
|
||||
"status_id": 1
|
||||
}'
|
||||
```
|
||||
|
||||
## 7. Просмотр списка тикетов
|
||||
|
||||
```bash
|
||||
curl -X GET http://localhost:8000/api/v1/tickets \
|
||||
-H "Authorization: Bearer $TOKEN"
|
||||
```
|
||||
|
||||
## 8. Тестирование через Swagger UI
|
||||
|
||||
Откройте http://localhost:8000/docs в браузере и взаимодействуйте с API через интерактивную документацию.
|
||||
|
||||
## 9. Запуск тестов
|
||||
|
||||
```bash
|
||||
# Все тесты
|
||||
pytest tests/ -v
|
||||
|
||||
# С покрытием
|
||||
pytest tests/ --cov=app --cov-report=html
|
||||
```
|
||||
|
||||
## 10. Миграция данных из ManageEngine
|
||||
|
||||
```bash
|
||||
# 1. Запустить extract_mssql.py (нужен доступ к ManageEngine MSSQL)
|
||||
python migrations/scripts/extract_mssql.py
|
||||
|
||||
# 2. Запустить transform_data.py для преобразования
|
||||
python migrations/scripts/transform_data.py
|
||||
|
||||
# 3. Запустить load_postgres.py для загрузки в PostgreSQL
|
||||
python migrations/scripts/load_postgres.py
|
||||
|
||||
# 4. Запустить validate_migration.py для проверки
|
||||
python migrations/scripts/validate_migration.py
|
||||
```
|
||||
|
||||
## 11. Локальная разработка
|
||||
|
||||
```bash
|
||||
# 1. Создать виртуальное окружение
|
||||
python -m venv venv
|
||||
source venv/bin/activate # Windows: venv\Scripts\activate
|
||||
|
||||
# 2. Установить зависимости
|
||||
pip install -r requirements-dev.txt
|
||||
|
||||
# 3. Настроить PostgreSQL (создать базу)
|
||||
createdb service_request
|
||||
|
||||
# 4. Инициализировать базу
|
||||
python -m app.core.database
|
||||
|
||||
# 5. Запустить приложение
|
||||
uvicorn app.main:app --reload --host 0.0.0.0 --port 8000
|
||||
|
||||
# 6. Запуск workers
|
||||
celery -A app.workers.celery_app worker --loglevel=info -Q email,sms
|
||||
```
|
||||
|
||||
## 12. Доступные API endpoints
|
||||
|
||||
### Authentication
|
||||
- `POST /api/v1/auth/register` - Регистрация
|
||||
- `POST /api/v1/auth/login` - Вход
|
||||
- `GET /api/v1/auth/me` - Текущий пользователь
|
||||
|
||||
### Tickets
|
||||
- `GET /api/v1/tickets` - Список тикетов
|
||||
- `GET /api/v1/tickets/{id}` - Детали тикета
|
||||
- `POST /api/v1/tickets` - Создать тикет
|
||||
- `PUT /api/v1/tickets/{id}` - Обновить тикет
|
||||
- `DELETE /api/v1/tickets/{id}` - Удалить тикет
|
||||
- `GET /api/v1/tickets/{id}/comments` - Комментарии к тикету
|
||||
|
||||
### Users
|
||||
- `GET /api/v1/users` - Список пользователей
|
||||
- `GET /api/v1/users/me` - Текущий пользователь
|
||||
- `GET /api/v1/users/{id}` - Детали пользователя
|
||||
|
||||
### Reference Data (Справочники)
|
||||
- `GET/POST /api/v1/reference/roles` - Роли
|
||||
- `GET/POST /api/v1/reference/statuses` - Статусы
|
||||
- `GET/POST /api/v1/reference/priorities` - Приоритеты
|
||||
- `GET/POST /api/v1/reference/categories` - Категории
|
||||
- `GET/POST /api/v1/reference/companies` - Компании
|
||||
- `GET/POST /api/v1/reference/locations` - Локации
|
||||
- `GET/POST /api/v1/reference/departments` - Отделы
|
||||
|
||||
### Notifications (Уведомления)
|
||||
- `GET /api/v1/notifications` - Уведомления пользователя
|
||||
- `PUT /api/v1/notifications/{id}/read` - Отметить как прочитанное
|
||||
- `PUT /api/v1/notifications/read-all` - Отметить все как прочитанные
|
||||
- `DELETE /api/v1/notifications/{id}` - Удалить уведомление
|
||||
|
||||
### Health
|
||||
- `GET /health` - Health check
|
||||
- `GET /health/db` - Проверка базы данных
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
### Database connection issues
|
||||
```bash
|
||||
# Проверить статус PostgreSQL
|
||||
docker-compose ps db
|
||||
|
||||
# Посмотреть логи базы
|
||||
docker-compose logs db
|
||||
|
||||
# Рестарт базы
|
||||
docker-compose restart db
|
||||
```
|
||||
|
||||
### Port conflicts
|
||||
```bash
|
||||
# Изменить порт в docker-compose.yml
|
||||
ports:
|
||||
- "8001:8000" # Вместо 8000:8000
|
||||
```
|
||||
|
||||
### Accessing RabbitMQ Management
|
||||
http://localhost:15672 (guest/guest)
|
||||
|
||||
## Development Checklist
|
||||
|
||||
- [x] Configure environment variables
|
||||
- [x] Set up PostgreSQL database
|
||||
- [x] Start Docker services
|
||||
- [x] Create admin user
|
||||
- [x] Test API endpoints
|
||||
- [x] Run migrations
|
||||
- [ ] Start Celery workers
|
||||
- [ ] Set up monitoring
|
||||
|
||||
## Production Deployment
|
||||
|
||||
### 1. Build Docker image
|
||||
```bash
|
||||
docker build -t service-request-system:latest .
|
||||
```
|
||||
|
||||
### 2. Create docker-compose.prod.yml
|
||||
```yaml
|
||||
version: '3.8'
|
||||
|
||||
services:
|
||||
app:
|
||||
image: service-request-system:latest
|
||||
environment:
|
||||
- DATABASE_URL=postgresql://user:password@db:5432/service_request
|
||||
# ... другие параметры
|
||||
deploy:
|
||||
replicas: 3
|
||||
resources:
|
||||
limits:
|
||||
cpus: '1.0'
|
||||
memory: 512M
|
||||
```
|
||||
|
||||
### 3. Deploy with Swarm
|
||||
```bash
|
||||
docker stack deploy -c docker-compose.prod.yml service-request
|
||||
```
|
||||
|
||||
## Support
|
||||
|
||||
Для вопросов обращайтесь в документацию или к команде разработки.
|
||||
@@ -0,0 +1,302 @@
|
||||
# Service Request System
|
||||
|
||||
Система обработки заявок с интеграцией почты, SMS и миграцией из ManageEngine ServiceDesk Plus 10.
|
||||
|
||||
## Технологический стек
|
||||
|
||||
- **Backend**: Python 3.11+ + FastAPI
|
||||
- **Database**: PostgreSQL 15 + SQLAlchemy ORM
|
||||
- **Migration**: Alembic
|
||||
- **Authentication**: JWT
|
||||
- **Message Queue**: RabbitMQ + Celery
|
||||
- **Caching**: Redis
|
||||
- **SMS**: Twilio
|
||||
- **Email**: SMTP/IMAP
|
||||
|
||||
## Требования
|
||||
|
||||
- Python 3.11+
|
||||
- Docker
|
||||
- Docker Compose
|
||||
|
||||
## Быстрый старт
|
||||
|
||||
### 1. Клонирование и настройка
|
||||
|
||||
```bash
|
||||
# Склонировать проект
|
||||
cd service-request-system
|
||||
|
||||
# Создать .env файл на основе .env.example
|
||||
cp .env.example .env
|
||||
|
||||
# Заполнить .env с вашими значениями
|
||||
nano .env
|
||||
```
|
||||
|
||||
### 2. Запуск через Docker Compose
|
||||
|
||||
```bash
|
||||
# Запуск всех сервисов
|
||||
docker-compose up -d
|
||||
|
||||
# Проверка статуса
|
||||
docker-compose ps
|
||||
|
||||
# Логи приложения
|
||||
docker-compose logs -f app
|
||||
```
|
||||
|
||||
### 3. Создание суперпользователя
|
||||
|
||||
```bash
|
||||
docker-compose exec app python -m scripts.create_admin
|
||||
```
|
||||
|
||||
### 4. Доступ к сервисам
|
||||
|
||||
- **API**: http://localhost:8000
|
||||
- **Swagger UI**: http://localhost:8000/docs
|
||||
- **RabbitMQ Management**: http://localhost:15672 (guest/guest)
|
||||
|
||||
## API Endpoints
|
||||
|
||||
### Authentication
|
||||
- `POST /api/v1/auth/register` - Регистрация нового пользователя
|
||||
- `POST /api/v1/auth/login` - Вход в систему
|
||||
- `GET /api/v1/auth/me` - Текущий пользователь
|
||||
|
||||
### Tickets
|
||||
- `GET /api/v1/tickets` - Список тикетов (с пагинацией)
|
||||
- `GET /api/v1/tickets/{ticket_id}` - Детали тикета
|
||||
- `POST /api/v1/tickets` - Создать тикет
|
||||
- `PUT /api/v1/tickets/{ticket_id}` - Обновить тикет
|
||||
- `DELETE /api/v1/tickets/{ticket_id}` - Удалить тикет
|
||||
- `GET /api/v1/tickets/{ticket_id}/comments` - Комментарии к тикету
|
||||
|
||||
### Users
|
||||
- `GET /api/v1/users` - Список пользователей
|
||||
- `GET /api/v1/users/me` - Текущий пользователь
|
||||
- `GET /api/v1/users/{user_id}` - Детали пользователя
|
||||
|
||||
### Reference Data (Справочники)
|
||||
- `GET/POST /api/v1/reference/roles` - Роли
|
||||
- `GET/POST /api/v1/reference/statuses` - Статусы
|
||||
- `GET/POST /api/v1/reference/priorities` - Приоритеты
|
||||
- `GET/POST /api/v1/reference/categories` - Категории
|
||||
- `GET/POST /api/v1/reference/companies` - Компании
|
||||
- `GET/POST /api/v1/reference/locations` - Локации
|
||||
- `GET/POST /api/v1/reference/departments` - Отделы
|
||||
|
||||
### Notifications (Уведомления)
|
||||
- `GET /api/v1/notifications` - Уведомления пользователя
|
||||
- `PUT /api/v1/notifications/{id}/read` - Отметить как прочитанное
|
||||
- `PUT /api/v1/notifications/read-all` - Отметить все как прочитанные
|
||||
- `DELETE /api/v1/notifications/{id}` - Удалить уведомление
|
||||
|
||||
## Миграция данных
|
||||
|
||||
### Подготовка к миграции
|
||||
|
||||
Убедитесь, что:
|
||||
1. Установлены ODBC драйверы для MSSQL
|
||||
2. Есть доступ к базе ManageEngine
|
||||
3. Соответствующие пользователи созданы
|
||||
|
||||
### Выполнение миграции
|
||||
|
||||
```bash
|
||||
# Извлечение данных из ManageEngine
|
||||
python migrations/scripts/extract_mssql.py
|
||||
|
||||
# Преобразование и загрузка в PostgreSQL
|
||||
python migrations/scripts/transform_and_load.py
|
||||
|
||||
# Валидация миграции
|
||||
python migrations/scripts/validate_migration.py
|
||||
```
|
||||
|
||||
### Ручная миграция через MSSQL
|
||||
|
||||
```sql
|
||||
-- Настройка ODBC в ODBC Data Sources
|
||||
-- DRIVER={ODBC Driver 17 for SQL Server};
|
||||
|
||||
-- Пример извлечения данных
|
||||
SELECT * INTO tickets_migrated
|
||||
FROM Tickets;
|
||||
```
|
||||
|
||||
## Разработка
|
||||
|
||||
### Локальная разработка
|
||||
|
||||
```bash
|
||||
# Создание виртуального окружения
|
||||
python -m venv venv
|
||||
source venv/bin/activate # Windows: venv\Scripts\activate
|
||||
|
||||
# Установка зависимостей
|
||||
pip install -r requirements-dev.txt
|
||||
|
||||
# Создание базы данных
|
||||
alembic upgrade head
|
||||
|
||||
# Запуск приложения
|
||||
uvicorn app.main:app --reload --host 0.0.0.0 --port 8000
|
||||
|
||||
# Запуск тестов
|
||||
pytest tests/ -v
|
||||
|
||||
# Запуск кодефинса
|
||||
black app/
|
||||
ruff check app/
|
||||
pyright app/
|
||||
```
|
||||
|
||||
### Docker разработка
|
||||
|
||||
```bash
|
||||
# Запуск в режиме разработки
|
||||
docker-compose up -d --build
|
||||
|
||||
# Перезапуск после изменений
|
||||
docker-compose restart app
|
||||
```
|
||||
|
||||
## Структура проекта
|
||||
|
||||
```
|
||||
service-request-system/
|
||||
├── app/
|
||||
│ ├── api/ # API endpoints
|
||||
│ │ └── v1/
|
||||
│ │ └── routes/ # Route handlers
|
||||
│ ├── core/ # Core functionality (security, database, etc.)
|
||||
│ │ ├── auth.py # Authentication dependencies
|
||||
│ │ ├── database.py # Database utilities
|
||||
│ │ ├── security.py # JWT and password utilities
|
||||
│ │ └── middleware.py # Security middleware
|
||||
│ ├── models/ # SQLAlchemy models
|
||||
│ ├── schemas/ # Pydantic schemas
|
||||
│ ├── services/ # Business logic
|
||||
│ ├── integrations/ # External integrations (email, SMS, etc.)
|
||||
│ ├── workers/ # Celery workers
|
||||
│ ├── repositories/ # Data access layer
|
||||
│ └── settings.py # Application settings
|
||||
├── migrations/ # Alembic migrations
|
||||
│ ├── alembic/ # Alembic configuration
|
||||
│ └── scripts/ # Migration scripts (MSSQL -> PostgreSQL)
|
||||
├── tests/ # Test suite
|
||||
├── docker-compose.yml # Docker Compose configuration
|
||||
├── Dockerfile # Docker build file
|
||||
└── requirements.txt # Python dependencies
|
||||
```
|
||||
|
||||
## Настройка
|
||||
|
||||
### .env файл
|
||||
|
||||
```bash
|
||||
# Database
|
||||
DATABASE_URL=postgresql://user:password@localhost:5432/service_request
|
||||
|
||||
# Redis
|
||||
REDIS_URL=redis://localhost:6379/0
|
||||
|
||||
# RabbitMQ
|
||||
RABBITMQ_URL=amqp://guest:guest@localhost:5672/
|
||||
|
||||
# JWT
|
||||
JWT_SECRET_KEY=your-secret-key-here
|
||||
JWT_ALGORITHM=HS256
|
||||
JWT_ACCESS_TOKEN_EXPIRE_MINUTES=30
|
||||
|
||||
# Email
|
||||
SMTP_SERVER=smtp.gmail.com
|
||||
SMTP_PORT=465
|
||||
SMTP_USERNAME=your-email@gmail.com
|
||||
SMTP_PASSWORD=your-app-password
|
||||
EMAIL_FROM=your-email@gmail.com
|
||||
|
||||
# SMS
|
||||
TWILIO_ACCOUNT_SID=your-twilio-account-sid
|
||||
TWILIO_AUTH_TOKEN=your-twilio-auth-token
|
||||
TWILIO_FROM_NUMBER=+15017250604
|
||||
|
||||
# Application
|
||||
APP_ENV=development
|
||||
APP_DEBUG=True
|
||||
APP_CORS_ORIGINS=http://localhost:3000,http://localhost:5173
|
||||
|
||||
# Migration
|
||||
MANAGEENGINE_CONNECTION_STRING=DRIVER={ODBC Driver 17 for SQL Server};SERVER=manageengine_server;DATABASE=ManageEngineSDP;UID=admin;PWD=password
|
||||
```
|
||||
|
||||
## Мониторинг и логи
|
||||
|
||||
### Логи приложения
|
||||
|
||||
```bash
|
||||
# Docker
|
||||
docker-compose logs -f app
|
||||
|
||||
# Логи Redis
|
||||
docker-compose logs -f redis
|
||||
|
||||
# Логи RabbitMQ
|
||||
docker-compose logs -f rabbitmq
|
||||
```
|
||||
|
||||
### Health check
|
||||
|
||||
```bash
|
||||
curl http://localhost:8000/health
|
||||
```
|
||||
|
||||
## Безопасность
|
||||
|
||||
- Все пароли хешируются через bcrypt
|
||||
- JWT токены используются для аутентификации
|
||||
- Включены заголовки безопасности (CSP, XSS-Protection)
|
||||
- SQL инъекции защищены через ORM
|
||||
|
||||
## Тестирование
|
||||
|
||||
```bash
|
||||
# Все тесты
|
||||
pytest tests/ -v
|
||||
|
||||
# С покрытием
|
||||
pytest tests/ --cov=app --cov-report=html
|
||||
|
||||
# Только определенные тесты
|
||||
pytest tests/test_api/test_tickets.py -v
|
||||
```
|
||||
|
||||
## Деплоймент
|
||||
|
||||
### Docker Production
|
||||
|
||||
```bash
|
||||
# Сборка образа
|
||||
docker build -t service-request-system:latest .
|
||||
|
||||
# Запуск production
|
||||
docker-compose -f docker-compose.prod.yml up -d
|
||||
```
|
||||
|
||||
### Kubernetes
|
||||
|
||||
См. файлы в `k8s/` директории (для продакшена).
|
||||
|
||||
## Поддержка
|
||||
|
||||
Для вопросов и проблем:
|
||||
1. Проверьте логи: `docker-compose logs app`
|
||||
2. Проверьте здоровье: `curl http://localhost:8000/health`
|
||||
3. Обратитесь к документации API: http://localhost:8000/docs
|
||||
|
||||
## Лицензия
|
||||
|
||||
[Ваша лицензия]
|
||||
@@ -0,0 +1,111 @@
|
||||
# ALEMBIC.ini
|
||||
|
||||
# A generic, single database configuration.
|
||||
|
||||
[alembic]
|
||||
# path to migration scripts
|
||||
script_location = migrations/alembic
|
||||
|
||||
# template used to generate migration file names; The default value is %%(rev)s_%%(slug)s
|
||||
file_template = %%(year)d%%(month).2d%%(day).2d_%%(hour).2d%%(minute).2d-%%(rev)s_%%(slug)s
|
||||
|
||||
# sys.path path, will be prepended to sys.path if present.
|
||||
prepend_sys_path = .
|
||||
|
||||
# timezone to use when rendering the date within the migration file
|
||||
# as well as the filename.
|
||||
# If specified, requires the python>=3.9 or backports.zoneinfo library.
|
||||
# timezone =
|
||||
|
||||
# max length of characters to apply to the
|
||||
# "slug" field
|
||||
# truncate_slug_length = 40
|
||||
|
||||
# set to 'true' to run the environment during
|
||||
# the 'revision' command, regardless of autogenerate
|
||||
# revision_environment = false
|
||||
|
||||
# set to 'true' to allow .pyc and .pyo files without
|
||||
# a source .py file to be detected as revisions in the
|
||||
# versions/ directory
|
||||
# sourceless = false
|
||||
|
||||
# version location specification; This defaults
|
||||
# to migrations/versions. When using multiple version
|
||||
# directories, initial revisions must be specified with --version-path.
|
||||
# The path separator used here should be the separator specified by "version_path_separator" below.
|
||||
# version_locations = %(here)s/bar:%(here)s/bat:migrations/versions
|
||||
|
||||
# version path separator; As mentioned above, this is the character used to split
|
||||
# version_locations. The default within new alembic.ini files is "os", which uses os.pathsep.
|
||||
# If this key is omitted entirely, it falls back to the legacy behavior of splitting on spaces and/or commas.
|
||||
# Valid values for version_path_separator are:
|
||||
#
|
||||
# version_path_separator = :
|
||||
# version_path_separator = ;
|
||||
# version_path_separator = space
|
||||
version_path_separator = os # Use os.pathsep. Default configuration used for new projects.
|
||||
|
||||
# set to 'true' to search source files recursively
|
||||
# in each "version_locations" directory
|
||||
# new in Alembic version 1.10
|
||||
# recursive_version_locations = false
|
||||
|
||||
# the output encoding used when revision files
|
||||
# are written from script.py.mako
|
||||
# output_encoding = utf-8
|
||||
|
||||
# sqlalchemy.url is set dynamically in env.py from app settings
|
||||
|
||||
|
||||
[post_write_hooks]
|
||||
# post_write_hooks defines scripts or Python functions that are run
|
||||
# on newly generated revision scripts. See the documentation for further
|
||||
# detail and examples
|
||||
|
||||
# format using "black" - use the console_scripts runner, against the "black" entrypoint
|
||||
# hooks = black
|
||||
# black.type = console_scripts
|
||||
# black.entrypoint = black
|
||||
# black.options = -l 79 REVISION_SCRIPT_FILENAME
|
||||
|
||||
# lint with attempts to fix using "ruff" - use the exec runner, execute a binary
|
||||
# hooks = ruff
|
||||
# ruff.type = exec
|
||||
# ruff.executable = %(here)s/.venv/bin/ruff
|
||||
# ruff.options = --fix REVISION_SCRIPT_FILENAME
|
||||
|
||||
# Logging configuration
|
||||
[loggers]
|
||||
keys = root,sqlalchemy,alembic
|
||||
|
||||
[handlers]
|
||||
keys = console
|
||||
|
||||
[formatters]
|
||||
keys = generic
|
||||
|
||||
[logger_root]
|
||||
level = WARN
|
||||
handlers = console
|
||||
qualname =
|
||||
|
||||
[logger_sqlalchemy]
|
||||
level = WARN
|
||||
handlers =
|
||||
qualname = sqlalchemy.engine
|
||||
|
||||
[logger_alembic]
|
||||
level = INFO
|
||||
handlers =
|
||||
qualname = alembic
|
||||
|
||||
[handler_console]
|
||||
class = StreamHandler
|
||||
args = (sys.stderr,)
|
||||
level = NOTSET
|
||||
formatter = generic
|
||||
|
||||
[formatter_generic]
|
||||
format = %(levelname)-5.5s [%(name)s] %(message)s
|
||||
datefmt = %H:%M:%S
|
||||
@@ -0,0 +1,3 @@
|
||||
"""App package."""
|
||||
|
||||
__version__ = "1.0.0"
|
||||
@@ -0,0 +1,5 @@
|
||||
"""Core module for API."""
|
||||
|
||||
from app.api.v1 import routes
|
||||
|
||||
__all__ = ["routes"]
|
||||
@@ -0,0 +1,5 @@
|
||||
"""API v1 package."""
|
||||
|
||||
from app.api.v1 import routes
|
||||
|
||||
__all__ = ["routes"]
|
||||
@@ -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"}
|
||||
@@ -0,0 +1,5 @@
|
||||
"""Configuration settings - delegates to app.settings."""
|
||||
|
||||
from 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",
|
||||
]
|
||||