phase-8: polish, global search, audit log, packaging, and demo docs
This commit is contained in:
@@ -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,
|
||||
}
|
||||
Reference in New Issue
Block a user