phase-8: polish, global search, audit log, packaging, and demo docs

This commit is contained in:
Atharv1705
2026-11-12 15:01:18 +05:30
parent 0b0f550eff
commit 0a2db8454d
34 changed files with 1804 additions and 88 deletions
+16
View File
@@ -0,0 +1,16 @@
FROM python:3.13-slim
WORKDIR /app
ENV PYTHONDONTWRITEBYTECODE=1
ENV PYTHONUNBUFFERED=1
COPY requirements.txt .
RUN pip install --no-cache-dir -r requirements.txt
COPY . .
RUN mkdir -p /app/data/uploads
EXPOSE 8000
CMD ["uvicorn", "app.main:app", "--host", "0.0.0.0", "--port", "8000"]
+4
View File
@@ -14,6 +14,7 @@ from .models import Base
from .routers import (
assets,
attachments,
audit,
auth,
calibration,
complaints,
@@ -26,6 +27,7 @@ from .routers import (
notifications,
pm,
reports,
search,
settings,
users,
visits,
@@ -126,3 +128,5 @@ app.include_router(visits.router, prefix="/api")
app.include_router(notifications.router, prefix="/api")
app.include_router(dashboard.router, prefix="/api")
app.include_router(reports.router, prefix="/api")
app.include_router(search.router, prefix="/api")
app.include_router(audit.router, prefix="/api")
+13 -13
View File
@@ -13,14 +13,14 @@ class Asset(Base):
asset_code: Mapped[str] = mapped_column(String(60), unique=True, index=True, nullable=False)
serial_no: Mapped[str] = mapped_column(String(100), index=True, nullable=False)
name: Mapped[str] = mapped_column(String(200), nullable=False)
category_id: Mapped[int] = mapped_column(ForeignKey("categories.id"), nullable=False)
department_id: Mapped[int] = mapped_column(ForeignKey("departments.id"), nullable=False)
location_id: Mapped[int] = mapped_column(ForeignKey("locations.id"), nullable=False)
category_id: Mapped[int] = mapped_column(ForeignKey("categories.id"), index=True, nullable=False)
department_id: Mapped[int] = mapped_column(ForeignKey("departments.id"), index=True, nullable=False)
location_id: Mapped[int] = mapped_column(ForeignKey("locations.id"), index=True, nullable=False)
supplier_id: Mapped[Optional[int]] = mapped_column(ForeignKey("vendors.id"), nullable=True)
purchase_value: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
purchase_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
installation_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
status: Mapped[str] = mapped_column(String(40), default="in_service", nullable=False)
status: Mapped[str] = mapped_column(String(40), default="in_service", index=True, nullable=False)
criticality: Mapped[str] = mapped_column(String(30), default="non_critical", nullable=False)
requires_calibration: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
insurance_applicable: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
@@ -40,11 +40,11 @@ class Contract(Base):
__tablename__ = "contracts"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
asset_id: Mapped[int] = mapped_column(ForeignKey("assets.id"), nullable=False)
asset_id: Mapped[int] = mapped_column(ForeignKey("assets.id"), index=True, nullable=False)
contract_type: Mapped[str] = mapped_column(String(20), nullable=False)
provider_id: Mapped[int] = mapped_column(ForeignKey("vendors.id"), nullable=False)
start_date: Mapped[date] = mapped_column(Date, nullable=False)
end_date: Mapped[date] = mapped_column(Date, nullable=False)
start_date: Mapped[date] = mapped_column(Date, index=True, nullable=False)
end_date: Mapped[date] = mapped_column(Date, index=True, nullable=False)
coverage_period_text: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
renewed_from_id: Mapped[Optional[int]] = mapped_column(ForeignKey("contracts.id"), nullable=True)
is_superseded: Mapped[bool] = mapped_column(Boolean, default=False, nullable=False)
@@ -62,10 +62,10 @@ class Warranty(Base):
__tablename__ = "warranties"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
asset_id: Mapped[int] = mapped_column(ForeignKey("assets.id"), nullable=False)
asset_id: Mapped[int] = mapped_column(ForeignKey("assets.id"), index=True, nullable=False)
duration_months: Mapped[int] = mapped_column(Integer, nullable=False)
start_date: Mapped[date] = mapped_column(Date, nullable=False)
end_date: Mapped[date] = mapped_column(Date, nullable=False)
start_date: Mapped[date] = mapped_column(Date, index=True, nullable=False)
end_date: Mapped[date] = mapped_column(Date, index=True, nullable=False)
provider_id: Mapped[Optional[int]] = mapped_column(ForeignKey("vendors.id"), nullable=True)
remarks: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, nullable=False)
@@ -81,11 +81,11 @@ class InsurancePolicy(Base):
__tablename__ = "insurance_policies"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
asset_id: Mapped[int] = mapped_column(ForeignKey("assets.id"), nullable=False)
asset_id: Mapped[int] = mapped_column(ForeignKey("assets.id"), index=True, nullable=False)
insurer_id: Mapped[int] = mapped_column(ForeignKey("vendors.id"), nullable=False)
policy_no: Mapped[str] = mapped_column(String(100), nullable=False)
start_date: Mapped[date] = mapped_column(Date, nullable=False)
end_date: Mapped[date] = mapped_column(Date, nullable=False)
start_date: Mapped[date] = mapped_column(Date, index=True, nullable=False)
end_date: Mapped[date] = mapped_column(Date, index=True, nullable=False)
coverage_amount: Mapped[Optional[float]] = mapped_column(Float, nullable=True)
remarks: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, nullable=False)
+4 -4
View File
@@ -11,23 +11,23 @@ class Complaint(Base):
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
complaint_no: Mapped[str] = mapped_column(String(60), unique=True, index=True, nullable=False)
asset_id: Mapped[int] = mapped_column(ForeignKey("assets.id"), nullable=False)
asset_id: Mapped[int] = mapped_column(ForeignKey("assets.id"), index=True, nullable=False)
description: Mapped[str] = mapped_column(Text, nullable=False)
breakdown_details: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
priority: Mapped[str] = mapped_column(String(30), default="non_critical", nullable=False)
notes: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
registered_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, nullable=False)
registered_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, index=True, nullable=False)
registered_by_id: Mapped[int] = mapped_column(ForeignKey("users.id"), nullable=False)
received_by_id: Mapped[int] = mapped_column(ForeignKey("users.id"), nullable=False)
received_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)
assigned_to_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True)
assigned_to_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), index=True, nullable=True)
assigned_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)
attended_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True)
attended_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)
restored_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)
closed_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True)
closed_at: Mapped[Optional[datetime]] = mapped_column(DateTime(timezone=True), nullable=True)
call_status: Mapped[str] = mapped_column(String(30), default="open", nullable=False)
call_status: Mapped[str] = mapped_column(String(30), default="open", index=True, nullable=False)
closure_remarks: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
action_taken: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
root_cause: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
+6 -6
View File
@@ -32,9 +32,9 @@ class CalibrationRecord(Base):
__tablename__ = "calibration_records"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
asset_id: Mapped[int] = mapped_column(ForeignKey("assets.id"), nullable=False)
plan_id: Mapped[int] = mapped_column(ForeignKey("calibration_plans.id"), nullable=False)
due_date: Mapped[date] = mapped_column(Date, nullable=False)
asset_id: Mapped[int] = mapped_column(ForeignKey("assets.id"), index=True, nullable=False)
plan_id: Mapped[int] = mapped_column(ForeignKey("calibration_plans.id"), index=True, nullable=False)
due_date: Mapped[date] = mapped_column(Date, index=True, nullable=False)
completed_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
agency_id: Mapped[Optional[int]] = mapped_column(ForeignKey("vendors.id"), nullable=True)
certificate_no: Mapped[Optional[str]] = mapped_column(String(100), nullable=True)
@@ -77,9 +77,9 @@ class PMRecord(Base):
__tablename__ = "pm_records"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
schedule_id: Mapped[int] = mapped_column(ForeignKey("pm_schedules.id"), nullable=False)
asset_id: Mapped[int] = mapped_column(ForeignKey("assets.id"), nullable=False)
planned_date: Mapped[date] = mapped_column(Date, nullable=False)
schedule_id: Mapped[int] = mapped_column(ForeignKey("pm_schedules.id"), index=True, nullable=False)
asset_id: Mapped[int] = mapped_column(ForeignKey("assets.id"), index=True, nullable=False)
planned_date: Mapped[date] = mapped_column(Date, index=True, nullable=False)
completed_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
# Only "completed" or "rescheduled" is persisted; upcoming/due/overdue are computed at read time.
status: Mapped[Optional[str]] = mapped_column(String(30), nullable=True)
+4 -4
View File
@@ -28,10 +28,10 @@ class DemoEquipment(Base):
name: Mapped[str] = mapped_column(String(200), nullable=False)
equipment_type: Mapped[str] = mapped_column(String(100), nullable=False)
supplier_id: Mapped[int] = mapped_column(ForeignKey("vendors.id"), nullable=False)
department_id: Mapped[int] = mapped_column(ForeignKey("departments.id"), nullable=False)
department_id: Mapped[int] = mapped_column(ForeignKey("departments.id"), index=True, nullable=False)
location_id: Mapped[Optional[int]] = mapped_column(ForeignKey("locations.id"), nullable=True)
start_date: Mapped[date] = mapped_column(Date, nullable=False)
expected_return_date: Mapped[date] = mapped_column(Date, nullable=False)
expected_return_date: Mapped[date] = mapped_column(Date, index=True, nullable=False)
actual_return_date: Mapped[Optional[date]] = mapped_column(Date, nullable=True)
remarks: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, nullable=False)
@@ -48,9 +48,9 @@ class DepartmentVisit(Base):
__tablename__ = "department_visits"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
department_id: Mapped[int] = mapped_column(ForeignKey("departments.id"), nullable=False)
department_id: Mapped[int] = mapped_column(ForeignKey("departments.id"), index=True, nullable=False)
visited_by_id: Mapped[int] = mapped_column(ForeignKey("users.id"), nullable=False)
visit_date: Mapped[date] = mapped_column(Date, nullable=False)
visit_date: Mapped[date] = mapped_column(Date, index=True, nullable=False)
observations: Mapped[Optional[str]] = mapped_column(Text, nullable=True)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, nullable=False)
created_by_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True)
+8 -8
View File
@@ -10,8 +10,8 @@ class Attachment(Base):
__tablename__ = "attachments"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
entity_type: Mapped[str] = mapped_column(String(60), nullable=False)
entity_id: Mapped[int] = mapped_column(Integer, nullable=False)
entity_type: Mapped[str] = mapped_column(String(60), index=True, nullable=False)
entity_id: Mapped[int] = mapped_column(Integer, index=True, nullable=False)
original_name: Mapped[str] = mapped_column(String(255), nullable=False)
stored_name: Mapped[str] = mapped_column(String(255), nullable=False)
mime_type: Mapped[str] = mapped_column(String(120), nullable=False)
@@ -24,7 +24,7 @@ class Notification(Base):
__tablename__ = "notifications"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
type: Mapped[str] = mapped_column(String(60), nullable=False)
type: Mapped[str] = mapped_column(String(60), index=True, nullable=False)
severity: Mapped[str] = mapped_column(String(20), nullable=False)
title: Mapped[str] = mapped_column(String(200), nullable=False)
message: Mapped[str] = mapped_column(Text, nullable=False)
@@ -34,7 +34,7 @@ class Notification(Base):
target_role: Mapped[Optional[str]] = mapped_column(String(50), nullable=True)
target_user_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True)
dedupe_key: Mapped[str] = mapped_column(String(200), unique=True, nullable=False)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, nullable=False)
created_at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, index=True, nullable=False)
class NotificationRead(Base):
@@ -53,9 +53,9 @@ class AuditLog(Base):
__tablename__ = "audit_logs"
id: Mapped[int] = mapped_column(Integer, primary_key=True, autoincrement=True)
entity_type: Mapped[str] = mapped_column(String(60), nullable=False)
entity_id: Mapped[int] = mapped_column(Integer, nullable=False)
entity_type: Mapped[str] = mapped_column(String(60), index=True, nullable=False)
entity_id: Mapped[int] = mapped_column(Integer, index=True, nullable=False)
action: Mapped[str] = mapped_column(String(50), nullable=False)
changes_json: Mapped[str] = mapped_column(Text, nullable=False)
by_user_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), nullable=True)
at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, nullable=False)
by_user_id: Mapped[Optional[int]] = mapped_column(ForeignKey("users.id"), index=True, nullable=True)
at: Mapped[datetime] = mapped_column(DateTime(timezone=True), default=utc_now, index=True, nullable=False)
+4
View File
@@ -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",
+82
View File
@@ -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,
}
+36 -2
View File
@@ -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))
+84
View File
@@ -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
],
}
+8
View File
@@ -8,6 +8,7 @@ from sqlalchemy.orm import sessionmaker
from app.core.db import get_db
from app.main import app
from app.models import Base
from app.routers.auth import reset_login_rate_limiter
SQLALCHEMY_TEST_URL = "sqlite:///./data/test.db"
engine_test = create_engine(SQLALCHEMY_TEST_URL, connect_args={"check_same_thread": False})
@@ -111,3 +112,10 @@ def client(db):
finally:
c.close()
app.dependency_overrides.clear()
@pytest.fixture(autouse=True)
def _clear_login_rate_limiter():
reset_login_rate_limiter()
yield
reset_login_rate_limiter()
+153
View File
@@ -0,0 +1,153 @@
import pytest
from app.models import Asset, AuditLog, Base, Department, User
from app.routers.auth import MAX_LOGIN_ATTEMPTS, reset_login_rate_limiter
from app.seed.seed import seed_database
@pytest.fixture(scope="module", autouse=True)
def seeded_phase8_db(db, tmp_path_factory):
upload_dir = tmp_path_factory.mktemp("phase8_test_uploads")
seed_database(db, upload_dir=upload_dir)
return upload_dir
def _auth_headers(client, email: str) -> dict[str, str]:
res = client.post("/api/auth/login", json={"email": email, "password": "Demo@123"})
assert res.status_code == 200, res.text
return {"Authorization": f"Bearer {res.json()['access_token']}"}
def test_global_search_grouped_and_department_scoped(client, db):
bio_headers = _auth_headers(client, "bio@poona.demo")
dept_headers = _auth_headers(client, "dept@poona.demo")
dept_user = db.query(User).filter(User.email == "dept@poona.demo").first()
icu_dept = db.query(Department).filter(Department.id == dept_user.department_id).first()
assert dept_user is not None and icu_dept is not None
icu_asset = db.query(Asset).filter(Asset.department_id == icu_dept.id).first()
non_icu_asset = db.query(Asset).filter(Asset.department_id != icu_dept.id).first()
assert icu_asset is not None and non_icu_asset is not None
# Broad search returns grouped assets & complaints capped at 8 each
broad = client.get("/api/search?q=PHRC", headers=bio_headers)
assert broad.status_code == 200, broad.text
data = broad.json()
assert isinstance(data["assets"], list) and 0 < len(data["assets"]) <= 8
assert isinstance(data["complaints"], list) and len(data["complaints"]) <= 8
assert {"id", "asset_code", "name", "serial_no", "department_name", "status"}.issubset(
data["assets"][0].keys()
)
# Complaint search by prefix
cmp_search = client.get("/api/search?q=CMP", headers=bio_headers)
assert cmp_search.status_code == 200
assert len(cmp_search.json()["complaints"]) > 0
assert {
"id",
"complaint_no",
"asset_code",
"asset_name",
"department_name",
"call_status",
"priority",
}.issubset(cmp_search.json()["complaints"][0].keys())
# Department user sees ICU asset, cannot see non-ICU asset
icu_res = client.get(f"/api/search?q={icu_asset.asset_code}", headers=dept_headers)
assert icu_res.status_code == 200
assert any(a["asset_code"] == icu_asset.asset_code for a in icu_res.json()["assets"])
other_res = client.get(f"/api/search?q={non_icu_asset.asset_code}", headers=dept_headers)
assert other_res.status_code == 200
assert other_res.json()["assets"] == []
assert other_res.json()["complaints"] == []
# Empty query rejected
assert client.get("/api/search?q=", headers=bio_headers).status_code == 422
def test_audit_logs_rbac_and_filters(client, db):
admin_headers = _auth_headers(client, "admin@poona.demo")
for email in ("bio@poona.demo", "mgmt@poona.demo", "dept@poona.demo", "coord@poona.demo"):
headers = _auth_headers(client, email)
assert client.get("/api/audit-logs", headers=headers).status_code == 403
# Ensure there is at least one distinct AuditLog entry via API/DB
admin_user = db.query(User).filter(User.email == "admin@poona.demo").first()
assert admin_user is not None
log_entry = AuditLog(
entity_type="asset",
entity_id=9999,
action="phase8_audit_probe",
changes_json='{"status": {"old": "in_service", "new": "under_repair"}}',
by_user_id=admin_user.id,
)
db.add(log_entry)
db.commit()
res = client.get("/api/audit-logs?entity_type=asset&action=phase8_audit_probe", headers=admin_headers)
assert res.status_code == 200, res.text
body = res.json()
assert body["total"] >= 1
assert len(body["items"]) >= 1
first = body["items"][0]
assert first["entity_type"] == "asset"
assert first["action"] == "phase8_audit_probe"
assert first["by_user_id"] == admin_user.id
assert first["by_user_name"] == admin_user.name
assert "under_repair" in first["changes_json"]
# Search filter `q`
q_res = client.get("/api/audit-logs?q=phase8_audit_probe", headers=admin_headers)
assert q_res.status_code == 200
assert q_res.json()["total"] == 1
def test_login_rate_limiter_429_and_reset(client):
reset_login_rate_limiter()
for i in range(MAX_LOGIN_ATTEMPTS):
res = client.post(
"/api/auth/login",
json={"email": "ratelimit@poona.demo", "password": "WrongPassword"},
)
assert res.status_code == 401, f"Attempt {i + 1} unexpected status {res.status_code}"
# Attempt 16 triggers 429 RATE_LIMITED
blocked = client.post(
"/api/auth/login",
json={"email": "ratelimit@poona.demo", "password": "WrongPassword"},
)
assert blocked.status_code == 429
assert blocked.json()["code"] == "RATE_LIMITED"
# Reset restores login capability
reset_login_rate_limiter()
ok = client.post(
"/api/auth/login",
json={"email": "admin@poona.demo", "password": "Demo@123"},
)
assert ok.status_code == 200
def test_database_indexes_defined():
expected_indexed_columns = {
"assets": {"asset_code", "serial_no", "department_id", "category_id", "location_id", "status"},
"complaints": {"complaint_no", "asset_id", "registered_at", "call_status", "assigned_to_id"},
"contracts": {"asset_id", "start_date", "end_date"},
"warranties": {"asset_id", "start_date", "end_date"},
"insurance_policies": {"asset_id", "start_date", "end_date"},
"calibration_records": {"asset_id", "plan_id", "due_date"},
"pm_records": {"asset_id", "schedule_id", "planned_date"},
"demo_equipment": {"department_id", "expected_return_date"},
"department_visits": {"department_id", "visit_date"},
"attachments": {"entity_type", "entity_id"},
"notifications": {"created_at", "type"},
"audit_logs": {"entity_type", "entity_id", "by_user_id", "at"},
}
for table_name, cols in expected_indexed_columns.items():
table = Base.metadata.tables[table_name]
indexed = {col.name for idx in table.indexes for col in idx.columns}
missing = cols - indexed
assert not missing, f"Missing indexes on {table_name}: {missing}"