phase-8: polish, global search, audit log, packaging, and demo docs
This commit is contained in:
@@ -1,6 +1,7 @@
|
||||
from . import (
|
||||
assets,
|
||||
attachments,
|
||||
audit,
|
||||
auth,
|
||||
calibration,
|
||||
complaints,
|
||||
@@ -13,6 +14,7 @@ from . import (
|
||||
notifications,
|
||||
pm,
|
||||
reports,
|
||||
search,
|
||||
settings,
|
||||
users,
|
||||
visits,
|
||||
@@ -22,6 +24,7 @@ from . import (
|
||||
__all__ = [
|
||||
"assets",
|
||||
"attachments",
|
||||
"audit",
|
||||
"auth",
|
||||
"calibration",
|
||||
"complaints",
|
||||
@@ -34,6 +37,7 @@ __all__ = [
|
||||
"notifications",
|
||||
"pm",
|
||||
"reports",
|
||||
"search",
|
||||
"settings",
|
||||
"users",
|
||||
"visits",
|
||||
|
||||
@@ -0,0 +1,82 @@
|
||||
from datetime import date, datetime, time, timedelta, timezone
|
||||
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
from sqlalchemy import String, cast, or_
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..core.db import get_db
|
||||
from ..core.deps import require_roles
|
||||
from ..core.time_utils import KOLKATA
|
||||
from ..models import AuditLog, User
|
||||
from ..services.permissions import Role
|
||||
|
||||
router = APIRouter(prefix="/audit-logs", tags=["audit"])
|
||||
|
||||
|
||||
@router.get("")
|
||||
def list_audit_logs(
|
||||
entity_type: str | None = Query(None),
|
||||
by_user_id: int | None = Query(None),
|
||||
action: str | None = Query(None),
|
||||
date_from: date | None = Query(None),
|
||||
date_to: date | None = Query(None),
|
||||
q: str | None = Query(None),
|
||||
page: int = Query(1, ge=1),
|
||||
page_size: int = Query(100, ge=1, le=500),
|
||||
db: Session = Depends(get_db),
|
||||
_admin: User = Depends(require_roles(Role.system_admin)),
|
||||
):
|
||||
query = db.query(AuditLog, User.name).outerjoin(User, AuditLog.by_user_id == User.id)
|
||||
|
||||
if entity_type:
|
||||
query = query.filter(AuditLog.entity_type == entity_type.strip())
|
||||
if by_user_id is not None:
|
||||
query = query.filter(AuditLog.by_user_id == by_user_id)
|
||||
if action:
|
||||
query = query.filter(AuditLog.action == action.strip())
|
||||
if date_from is not None:
|
||||
dt_from_utc = KOLKATA.localize(
|
||||
datetime.combine(date_from, time(0, 0, 0))
|
||||
).astimezone(timezone.utc)
|
||||
query = query.filter(AuditLog.at >= dt_from_utc)
|
||||
if date_to is not None:
|
||||
dt_to_utc = KOLKATA.localize(
|
||||
datetime.combine(date_to + timedelta(days=1), time(0, 0, 0))
|
||||
).astimezone(timezone.utc)
|
||||
query = query.filter(AuditLog.at < dt_to_utc)
|
||||
if q and q.strip():
|
||||
pat = f"%{q.strip()}%"
|
||||
query = query.filter(
|
||||
or_(
|
||||
AuditLog.entity_type.ilike(pat),
|
||||
AuditLog.action.ilike(pat),
|
||||
AuditLog.changes_json.ilike(pat),
|
||||
cast(AuditLog.entity_id, String).ilike(pat),
|
||||
User.name.ilike(pat),
|
||||
)
|
||||
)
|
||||
|
||||
total = query.count()
|
||||
rows = (
|
||||
query.order_by(AuditLog.at.desc(), AuditLog.id.desc())
|
||||
.offset((page - 1) * page_size)
|
||||
.limit(page_size)
|
||||
.all()
|
||||
)
|
||||
|
||||
return {
|
||||
"items": [
|
||||
{
|
||||
"id": log.id,
|
||||
"entity_type": log.entity_type,
|
||||
"entity_id": log.entity_id,
|
||||
"action": log.action,
|
||||
"changes_json": log.changes_json,
|
||||
"by_user_id": log.by_user_id,
|
||||
"by_user_name": user_name or "System",
|
||||
"at": log.at,
|
||||
}
|
||||
for log, user_name in rows
|
||||
],
|
||||
"total": total,
|
||||
}
|
||||
@@ -1,7 +1,11 @@
|
||||
from fastapi import APIRouter, Depends, HTTPException, status
|
||||
from collections import defaultdict, deque
|
||||
import threading
|
||||
import time
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request, status
|
||||
from sqlalchemy.orm import Session, joinedload
|
||||
from ..core.db import get_db
|
||||
from ..core.deps import get_current_user
|
||||
from ..core.exceptions import CodedHTTPException
|
||||
from ..core.security import create_access_token, verify_password
|
||||
from ..models.masters import User
|
||||
from ..schemas.auth import LoginRequest, TokenResponse, UserOut
|
||||
@@ -9,6 +13,34 @@ from ..services.settings_service import get_demo_as_of_date
|
||||
|
||||
router = APIRouter(prefix="/auth", tags=["auth"])
|
||||
|
||||
MAX_LOGIN_ATTEMPTS = 15
|
||||
LOGIN_WINDOW_SECONDS = 60.0
|
||||
_login_attempts: dict[str, deque[float]] = defaultdict(deque)
|
||||
_rate_limit_lock = threading.Lock()
|
||||
|
||||
|
||||
def reset_login_rate_limiter() -> None:
|
||||
"""Clear sliding-window login attempt counters (used in tests)."""
|
||||
with _rate_limit_lock:
|
||||
_login_attempts.clear()
|
||||
|
||||
|
||||
def _enforce_login_rate_limit(client_ip: str, email_norm: str) -> None:
|
||||
now = time.monotonic()
|
||||
cutoff = now - LOGIN_WINDOW_SECONDS
|
||||
key = f"{client_ip}:{email_norm}"
|
||||
with _rate_limit_lock:
|
||||
attempts = _login_attempts[key]
|
||||
while attempts and attempts[0] <= cutoff:
|
||||
attempts.popleft()
|
||||
if len(attempts) >= MAX_LOGIN_ATTEMPTS:
|
||||
raise CodedHTTPException(
|
||||
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
|
||||
detail="Too many login attempts. Please wait a minute.",
|
||||
code="RATE_LIMITED",
|
||||
)
|
||||
attempts.append(now)
|
||||
|
||||
|
||||
def _build_user_out(user: User, db: Session) -> UserOut:
|
||||
return UserOut(
|
||||
@@ -24,8 +56,10 @@ def _build_user_out(user: User, db: Session) -> UserOut:
|
||||
|
||||
|
||||
@router.post("/login", response_model=TokenResponse)
|
||||
def login(payload: LoginRequest, db: Session = Depends(get_db)):
|
||||
def login(payload: LoginRequest, request: Request, db: Session = Depends(get_db)):
|
||||
email_norm = payload.email.strip().lower()
|
||||
client_ip = request.client.host if request.client else "unknown"
|
||||
_enforce_login_rate_limit(client_ip, email_norm)
|
||||
user = (
|
||||
db.query(User)
|
||||
.options(joinedload(User.department))
|
||||
|
||||
@@ -0,0 +1,84 @@
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
from sqlalchemy import or_
|
||||
from sqlalchemy.orm import Session, joinedload
|
||||
|
||||
from ..core.db import get_db
|
||||
from ..core.deps import get_current_user
|
||||
from ..models import Asset, Complaint, User
|
||||
from ..services.permissions import Role
|
||||
|
||||
router = APIRouter(prefix="/search", tags=["search"])
|
||||
|
||||
|
||||
@router.get("")
|
||||
def global_search(
|
||||
q: str = Query(..., min_length=1),
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user),
|
||||
):
|
||||
term = q.strip()
|
||||
if not term:
|
||||
return {"assets": [], "complaints": []}
|
||||
|
||||
pattern = f"%{term}%"
|
||||
is_dept_scoped = current_user.role == Role.department_user.value
|
||||
|
||||
asset_q = db.query(Asset).options(joinedload(Asset.department)).filter(
|
||||
or_(
|
||||
Asset.asset_code.ilike(pattern),
|
||||
Asset.name.ilike(pattern),
|
||||
Asset.serial_no.ilike(pattern),
|
||||
)
|
||||
)
|
||||
if is_dept_scoped:
|
||||
asset_q = asset_q.filter(Asset.department_id == current_user.department_id)
|
||||
assets = asset_q.order_by(Asset.asset_code.asc()).limit(8).all()
|
||||
|
||||
complaint_q = (
|
||||
db.query(Complaint)
|
||||
.join(Asset, Complaint.asset_id == Asset.id)
|
||||
.options(joinedload(Complaint.asset).joinedload(Asset.department))
|
||||
.filter(
|
||||
or_(
|
||||
Complaint.complaint_no.ilike(pattern),
|
||||
Complaint.description.ilike(pattern),
|
||||
Asset.asset_code.ilike(pattern),
|
||||
Asset.name.ilike(pattern),
|
||||
)
|
||||
)
|
||||
)
|
||||
if is_dept_scoped:
|
||||
complaint_q = complaint_q.filter(Asset.department_id == current_user.department_id)
|
||||
complaints = (
|
||||
complaint_q.order_by(Complaint.registered_at.desc(), Complaint.id.desc())
|
||||
.limit(8)
|
||||
.all()
|
||||
)
|
||||
|
||||
return {
|
||||
"assets": [
|
||||
{
|
||||
"id": a.id,
|
||||
"asset_code": a.asset_code,
|
||||
"name": a.name,
|
||||
"serial_no": a.serial_no,
|
||||
"department_name": a.department.name if a.department else "—",
|
||||
"status": a.status,
|
||||
}
|
||||
for a in assets
|
||||
],
|
||||
"complaints": [
|
||||
{
|
||||
"id": c.id,
|
||||
"complaint_no": c.complaint_no,
|
||||
"asset_code": c.asset.asset_code if c.asset else "—",
|
||||
"asset_name": c.asset.name if c.asset else "—",
|
||||
"department_name": (
|
||||
c.asset.department.name if c.asset and c.asset.department else "—"
|
||||
),
|
||||
"call_status": c.call_status,
|
||||
"priority": c.priority,
|
||||
}
|
||||
for c in complaints
|
||||
],
|
||||
}
|
||||
Reference in New Issue
Block a user