phase-2: asset register, detail overview, asset picker, attachments
This commit is contained in:
@@ -58,11 +58,14 @@ cd backend
|
|||||||
| mgmt@poona.demo | Demo@123 | Management |
|
| mgmt@poona.demo | Demo@123 | Management |
|
||||||
| coord@poona.demo | Demo@123 | Coordinator |
|
| coord@poona.demo | Demo@123 | Coordinator |
|
||||||
|
|
||||||
## What exists now (Phase 1)
|
## What exists now (Phase 2)
|
||||||
- Complete SQLAlchemy 19-table data model across masters, assets, maintenance, complaints, operations, and system modules
|
- Complete SQLAlchemy 19-table data model across masters, assets, maintenance, complaints, operations, and system modules
|
||||||
- JWT authentication (`/api/auth/login`, `/api/auth/me`), RBAC permission matrix for 5 roles, and Quick Demo Login
|
- JWT authentication (`/api/auth/login`, `/api/auth/me`), RBAC permission matrix for 5 roles, and Quick Demo Login
|
||||||
- Admin Master Lists CRUD (`/masters`: Departments, Locations, Categories, Vendors, Users)
|
- Admin Master Lists CRUD (`/masters`: Departments, Locations, Categories, Vendors, Users)
|
||||||
- Typed System Settings (`/settings`) and TopBar "As of Date" Demo Clock (`POST /api/settings/demo-date`)
|
- Typed System Settings (`/settings`) and TopBar "As of Date" Demo Clock (`POST /api/settings/demo-date`)
|
||||||
|
- Asset Register (`/assets` & `/assets/:id`): full CRUD with duplicate asset code check (`409`), department scoping, coordinator field-level edit restrictions, 8-tab Asset Detail Overview, and audit logging
|
||||||
|
- Reusable `AssetPicker` (`/api/assets/lookup`) with warranty/condemned status badges
|
||||||
|
- Secure Document Attachments (`/api/attachments`: JPG/PNG/PDF validation with magic-byte check, 10 MB limit, authenticated preview/download, role-based upload/delete)
|
||||||
- Idempotent deterministic seed script (`python -m app.seed.seed`) populating realistic hospital demo data
|
- Idempotent deterministic seed script (`python -m app.seed.seed`) populating realistic hospital demo data
|
||||||
- React + TypeScript frontend app shell with role-filtered sidebar, route guards, DataTable, and Tailwind CSS + shadcn/ui
|
- React + TypeScript frontend app shell with role-filtered sidebar, route guards, DataTable, and Tailwind CSS + shadcn/ui
|
||||||
- Makefile for common tasks
|
- Makefile for common tasks
|
||||||
|
|||||||
@@ -0,0 +1,16 @@
|
|||||||
|
from fastapi import HTTPException, Request
|
||||||
|
from fastapi.responses import JSONResponse
|
||||||
|
|
||||||
|
|
||||||
|
class CodedHTTPException(HTTPException):
|
||||||
|
def __init__(self, status_code: int, detail: str, code: str):
|
||||||
|
super().__init__(status_code=status_code, detail=detail)
|
||||||
|
self.code = code
|
||||||
|
|
||||||
|
|
||||||
|
async def coded_http_exception_handler(request: Request, exc: CodedHTTPException) -> JSONResponse:
|
||||||
|
return JSONResponse(
|
||||||
|
status_code=exc.status_code,
|
||||||
|
content={"detail": exc.detail, "code": exc.code},
|
||||||
|
headers=exc.headers,
|
||||||
|
)
|
||||||
+6
-1
@@ -5,8 +5,9 @@ from fastapi import FastAPI, Request
|
|||||||
from fastapi.middleware.cors import CORSMiddleware
|
from fastapi.middleware.cors import CORSMiddleware
|
||||||
from fastapi.responses import JSONResponse
|
from fastapi.responses import JSONResponse
|
||||||
from .core.db import SessionLocal, engine
|
from .core.db import SessionLocal, engine
|
||||||
|
from .core.exceptions import CodedHTTPException, coded_http_exception_handler
|
||||||
from .models import Base
|
from .models import Base
|
||||||
from .routers import auth, health, masters, settings, users
|
from .routers import assets, attachments, auth, health, masters, settings, users
|
||||||
from .services.settings_service import ensure_default_settings
|
from .services.settings_service import ensure_default_settings
|
||||||
|
|
||||||
logging.basicConfig(
|
logging.basicConfig(
|
||||||
@@ -42,6 +43,8 @@ app.add_middleware(
|
|||||||
allow_headers=["*"],
|
allow_headers=["*"],
|
||||||
)
|
)
|
||||||
|
|
||||||
|
app.add_exception_handler(CodedHTTPException, coded_http_exception_handler)
|
||||||
|
|
||||||
|
|
||||||
@app.exception_handler(Exception)
|
@app.exception_handler(Exception)
|
||||||
async def global_exception_handler(request: Request, exc: Exception):
|
async def global_exception_handler(request: Request, exc: Exception):
|
||||||
@@ -57,3 +60,5 @@ app.include_router(auth.router, prefix="/api")
|
|||||||
app.include_router(settings.router, prefix="/api")
|
app.include_router(settings.router, prefix="/api")
|
||||||
app.include_router(masters.router, prefix="/api")
|
app.include_router(masters.router, prefix="/api")
|
||||||
app.include_router(users.router, prefix="/api")
|
app.include_router(users.router, prefix="/api")
|
||||||
|
app.include_router(assets.router, prefix="/api")
|
||||||
|
app.include_router(attachments.router, prefix="/api")
|
||||||
|
|||||||
@@ -1,3 +1,3 @@
|
|||||||
from . import auth, health, masters, settings, users
|
from . import assets, attachments, auth, health, masters, settings, users
|
||||||
|
|
||||||
__all__ = ["auth", "health", "masters", "settings", "users"]
|
__all__ = ["assets", "attachments", "auth", "health", "masters", "settings", "users"]
|
||||||
|
|||||||
@@ -0,0 +1,855 @@
|
|||||||
|
from datetime import date
|
||||||
|
from typing import Any, Optional
|
||||||
|
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
||||||
|
from sqlalchemy import or_
|
||||||
|
from sqlalchemy.exc import IntegrityError
|
||||||
|
from sqlalchemy.orm import Session, joinedload
|
||||||
|
|
||||||
|
from ..core.db import get_db
|
||||||
|
from ..core.deps import get_current_user, require_roles
|
||||||
|
from ..core.exceptions import CodedHTTPException
|
||||||
|
from ..core.time_utils import effective_today, format_date
|
||||||
|
from ..models import (
|
||||||
|
Asset,
|
||||||
|
Attachment,
|
||||||
|
CalibrationPlan,
|
||||||
|
CalibrationRecord,
|
||||||
|
Category,
|
||||||
|
Complaint,
|
||||||
|
Contract,
|
||||||
|
Department,
|
||||||
|
InsurancePolicy,
|
||||||
|
Location,
|
||||||
|
PMRecord,
|
||||||
|
PMSchedule,
|
||||||
|
User,
|
||||||
|
Vendor,
|
||||||
|
Warranty,
|
||||||
|
)
|
||||||
|
from ..schemas.assets import (
|
||||||
|
AssetCreate,
|
||||||
|
AssetListOut,
|
||||||
|
AssetLookupListOut,
|
||||||
|
AssetLookupOut,
|
||||||
|
AssetOut,
|
||||||
|
AssetOverviewOut,
|
||||||
|
AssetUpdate,
|
||||||
|
AttachmentSummaryOut,
|
||||||
|
CalibrationPlanSummaryOut,
|
||||||
|
CalibrationRecordSummaryOut,
|
||||||
|
ComplaintSummaryOut,
|
||||||
|
ContractSummaryOut,
|
||||||
|
InsuranceSummaryOut,
|
||||||
|
PMRecordSummaryOut,
|
||||||
|
PMScheduleSummaryOut,
|
||||||
|
WarrantySummaryOut,
|
||||||
|
)
|
||||||
|
from ..services.audit import log_audit
|
||||||
|
from ..services.calculations import compute_schedule_status, coverage_status
|
||||||
|
from ..services.permissions import Role
|
||||||
|
from ..services.settings_service import get_setting_value
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/assets", tags=["assets"])
|
||||||
|
|
||||||
|
COORDINATOR_ALLOWED_FIELDS = {"requires_calibration", "insurance_applicable", "remarks"}
|
||||||
|
|
||||||
|
|
||||||
|
def _lead_settings(db: Session) -> dict[str, int]:
|
||||||
|
return {
|
||||||
|
"warranty": int(get_setting_value(db, "warranty_expiry_alert_days")),
|
||||||
|
"contract": int(get_setting_value(db, "contract_expiry_alert_days")),
|
||||||
|
"insurance": int(get_setting_value(db, "insurance_expiry_alert_days")),
|
||||||
|
"calibration": int(get_setting_value(db, "calibration_due_window_days")),
|
||||||
|
"pm": int(get_setting_value(db, "pm_due_window_days")),
|
||||||
|
"red": int(get_setting_value(db, "contract_critical_alert_days")),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _preload_latest_relations(db: Session, asset_ids: list[int]) -> dict[str, dict[int, Any]]:
|
||||||
|
if not asset_ids:
|
||||||
|
return {
|
||||||
|
"warranty": {},
|
||||||
|
"contract": {},
|
||||||
|
"insurance": {},
|
||||||
|
"cal_plan": {},
|
||||||
|
"cal_open_rec": {},
|
||||||
|
"cal_last_rec": {},
|
||||||
|
}
|
||||||
|
|
||||||
|
warranties: dict[int, Warranty] = {}
|
||||||
|
for w in (
|
||||||
|
db.query(Warranty)
|
||||||
|
.filter(Warranty.asset_id.in_(asset_ids))
|
||||||
|
.order_by(Warranty.end_date.desc(), Warranty.id.desc())
|
||||||
|
.all()
|
||||||
|
):
|
||||||
|
if w.asset_id not in warranties:
|
||||||
|
warranties[w.asset_id] = w
|
||||||
|
|
||||||
|
contracts: dict[int, Contract] = {}
|
||||||
|
for c in (
|
||||||
|
db.query(Contract)
|
||||||
|
.filter(Contract.asset_id.in_(asset_ids), Contract.is_superseded.is_(False))
|
||||||
|
.order_by(Contract.end_date.desc(), Contract.id.desc())
|
||||||
|
.all()
|
||||||
|
):
|
||||||
|
if c.asset_id not in contracts:
|
||||||
|
contracts[c.asset_id] = c
|
||||||
|
|
||||||
|
insurances: dict[int, InsurancePolicy] = {}
|
||||||
|
for ins in (
|
||||||
|
db.query(InsurancePolicy)
|
||||||
|
.filter(InsurancePolicy.asset_id.in_(asset_ids))
|
||||||
|
.order_by(InsurancePolicy.end_date.desc(), InsurancePolicy.id.desc())
|
||||||
|
.all()
|
||||||
|
):
|
||||||
|
if ins.asset_id not in insurances:
|
||||||
|
insurances[ins.asset_id] = ins
|
||||||
|
|
||||||
|
cal_plans: dict[int, CalibrationPlan] = {
|
||||||
|
p.asset_id: p
|
||||||
|
for p in db.query(CalibrationPlan)
|
||||||
|
.filter(CalibrationPlan.asset_id.in_(asset_ids), CalibrationPlan.is_active.is_(True))
|
||||||
|
.all()
|
||||||
|
}
|
||||||
|
|
||||||
|
cal_open_recs: dict[int, CalibrationRecord] = {}
|
||||||
|
cal_last_recs: dict[int, CalibrationRecord] = {}
|
||||||
|
for rec in (
|
||||||
|
db.query(CalibrationRecord)
|
||||||
|
.filter(CalibrationRecord.asset_id.in_(asset_ids))
|
||||||
|
.order_by(CalibrationRecord.due_date.desc(), CalibrationRecord.id.desc())
|
||||||
|
.all()
|
||||||
|
):
|
||||||
|
if rec.asset_id not in cal_last_recs:
|
||||||
|
cal_last_recs[rec.asset_id] = rec
|
||||||
|
if rec.status != "completed" and rec.asset_id not in cal_open_recs:
|
||||||
|
cal_open_recs[rec.asset_id] = rec
|
||||||
|
|
||||||
|
return {
|
||||||
|
"warranty": warranties,
|
||||||
|
"contract": contracts,
|
||||||
|
"insurance": insurances,
|
||||||
|
"cal_plan": cal_plans,
|
||||||
|
"cal_open_rec": cal_open_recs,
|
||||||
|
"cal_last_rec": cal_last_recs,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _derive_asset_fields(
|
||||||
|
asset: Asset,
|
||||||
|
rels: dict[str, dict[int, Any]],
|
||||||
|
today: date,
|
||||||
|
leads: dict[str, int],
|
||||||
|
) -> dict[str, Any]:
|
||||||
|
w = rels["warranty"].get(asset.id)
|
||||||
|
if w:
|
||||||
|
w_status, w_sev = coverage_status(w.start_date, w.end_date, today, leads["warranty"], leads["red"])
|
||||||
|
w_end = w.end_date
|
||||||
|
else:
|
||||||
|
w_status, w_sev, w_end = "none", "none", None
|
||||||
|
|
||||||
|
c = rels["contract"].get(asset.id)
|
||||||
|
if c:
|
||||||
|
c_status, c_sev = coverage_status(c.start_date, c.end_date, today, leads["contract"], leads["red"])
|
||||||
|
c_type, c_end = c.contract_type, c.end_date
|
||||||
|
else:
|
||||||
|
c_status, c_sev, c_type, c_end = "none", "none", None, None
|
||||||
|
|
||||||
|
ins = rels["insurance"].get(asset.id)
|
||||||
|
if ins:
|
||||||
|
ins_status, _ = coverage_status(ins.start_date, ins.end_date, today, leads["insurance"], leads["red"])
|
||||||
|
ins_end = ins.end_date
|
||||||
|
else:
|
||||||
|
ins_status, ins_end = "none", None
|
||||||
|
|
||||||
|
plan = rels["cal_plan"].get(asset.id)
|
||||||
|
open_rec = rels["cal_open_rec"].get(asset.id)
|
||||||
|
last_rec = rels["cal_last_rec"].get(asset.id)
|
||||||
|
if open_rec is not None:
|
||||||
|
cal_due = open_rec.due_date
|
||||||
|
cal_status, cal_sev = compute_schedule_status(cal_due, open_rec.status, today, leads["calibration"], leads["red"])
|
||||||
|
elif plan is not None:
|
||||||
|
cal_due = plan.next_due_date
|
||||||
|
cal_status, cal_sev = compute_schedule_status(cal_due, None, today, leads["calibration"], leads["red"])
|
||||||
|
elif last_rec is not None:
|
||||||
|
cal_due = last_rec.due_date
|
||||||
|
cal_status, cal_sev = compute_schedule_status(cal_due, last_rec.status, today, leads["calibration"], leads["red"])
|
||||||
|
else:
|
||||||
|
cal_status, cal_due, cal_sev = "none", None, "none"
|
||||||
|
|
||||||
|
return {
|
||||||
|
"warranty_status": w_status,
|
||||||
|
"warranty_end_date": w_end,
|
||||||
|
"warranty_severity": w_sev,
|
||||||
|
"contract_status": c_status,
|
||||||
|
"contract_type": c_type,
|
||||||
|
"contract_end_date": c_end,
|
||||||
|
"contract_severity": c_sev,
|
||||||
|
"calibration_status": cal_status,
|
||||||
|
"calibration_due_date": cal_due,
|
||||||
|
"calibration_severity": cal_sev,
|
||||||
|
"insurance_status": ins_status,
|
||||||
|
"insurance_end_date": ins_end,
|
||||||
|
"_contract_obj": c,
|
||||||
|
"_insurance_obj": ins,
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def _to_asset_out(
|
||||||
|
asset: Asset,
|
||||||
|
rels: dict[str, dict[int, Any]],
|
||||||
|
today: date,
|
||||||
|
leads: dict[str, int],
|
||||||
|
) -> AssetOut:
|
||||||
|
d = _derive_asset_fields(asset, rels, today, leads)
|
||||||
|
return AssetOut(
|
||||||
|
id=asset.id,
|
||||||
|
asset_code=asset.asset_code,
|
||||||
|
serial_no=asset.serial_no,
|
||||||
|
name=asset.name,
|
||||||
|
category_id=asset.category_id,
|
||||||
|
category_name=asset.category.name if asset.category else None,
|
||||||
|
department_id=asset.department_id,
|
||||||
|
department_name=asset.department.name if asset.department else None,
|
||||||
|
location_id=asset.location_id,
|
||||||
|
location_name=asset.location.name if asset.location else None,
|
||||||
|
supplier_id=asset.supplier_id,
|
||||||
|
supplier_name=asset.supplier.name if asset.supplier else None,
|
||||||
|
purchase_value=asset.purchase_value,
|
||||||
|
purchase_date=asset.purchase_date,
|
||||||
|
installation_date=asset.installation_date,
|
||||||
|
status=asset.status,
|
||||||
|
criticality=asset.criticality,
|
||||||
|
requires_calibration=asset.requires_calibration,
|
||||||
|
insurance_applicable=asset.insurance_applicable,
|
||||||
|
remarks=asset.remarks,
|
||||||
|
warranty_status=d["warranty_status"],
|
||||||
|
warranty_end_date=d["warranty_end_date"],
|
||||||
|
warranty_severity=d["warranty_severity"],
|
||||||
|
contract_status=d["contract_status"],
|
||||||
|
contract_type=d["contract_type"],
|
||||||
|
contract_end_date=d["contract_end_date"],
|
||||||
|
contract_severity=d["contract_severity"],
|
||||||
|
calibration_status=d["calibration_status"],
|
||||||
|
calibration_due_date=d["calibration_due_date"],
|
||||||
|
calibration_severity=d["calibration_severity"],
|
||||||
|
insurance_status=d["insurance_status"],
|
||||||
|
insurance_end_date=d["insurance_end_date"],
|
||||||
|
created_at=asset.created_at,
|
||||||
|
updated_at=asset.updated_at,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def _validate_asset_fks(
|
||||||
|
db: Session,
|
||||||
|
category_id: int | None = None,
|
||||||
|
department_id: int | None = None,
|
||||||
|
location_id: int | None = None,
|
||||||
|
supplier_id: int | None = None,
|
||||||
|
) -> None:
|
||||||
|
if category_id is not None and not db.query(Category.id).filter(Category.id == category_id).first():
|
||||||
|
raise HTTPException(status_code=404, detail="Category not found.")
|
||||||
|
if department_id is not None and not db.query(Department.id).filter(Department.id == department_id).first():
|
||||||
|
raise HTTPException(status_code=404, detail="Department not found.")
|
||||||
|
if location_id is not None and not db.query(Location.id).filter(Location.id == location_id).first():
|
||||||
|
raise HTTPException(status_code=404, detail="Location not found.")
|
||||||
|
if supplier_id is not None and not db.query(Vendor.id).filter(Vendor.id == supplier_id).first():
|
||||||
|
raise HTTPException(status_code=404, detail="Supplier vendor not found.")
|
||||||
|
|
||||||
|
|
||||||
|
def _load_asset_with_joins(db: Session, asset_id: int) -> Asset | None:
|
||||||
|
return (
|
||||||
|
db.query(Asset)
|
||||||
|
.options(
|
||||||
|
joinedload(Asset.category),
|
||||||
|
joinedload(Asset.department),
|
||||||
|
joinedload(Asset.location),
|
||||||
|
joinedload(Asset.supplier),
|
||||||
|
)
|
||||||
|
.filter(Asset.id == asset_id)
|
||||||
|
.first()
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/lookup", response_model=AssetLookupListOut)
|
||||||
|
def lookup_assets(
|
||||||
|
q: str = "",
|
||||||
|
department_id: Optional[int] = None,
|
||||||
|
limit: int = Query(25, ge=1, le=100),
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current_user: User = Depends(get_current_user),
|
||||||
|
):
|
||||||
|
query = db.query(Asset).options(
|
||||||
|
joinedload(Asset.category),
|
||||||
|
joinedload(Asset.department),
|
||||||
|
joinedload(Asset.location),
|
||||||
|
joinedload(Asset.supplier),
|
||||||
|
)
|
||||||
|
if current_user.role == Role.department_user.value:
|
||||||
|
query = query.filter(Asset.department_id == current_user.department_id)
|
||||||
|
elif department_id is not None:
|
||||||
|
query = query.filter(Asset.department_id == department_id)
|
||||||
|
|
||||||
|
if q and q.strip():
|
||||||
|
like = f"%{q.strip()}%"
|
||||||
|
query = query.filter(
|
||||||
|
or_(
|
||||||
|
Asset.asset_code.ilike(like),
|
||||||
|
Asset.name.ilike(like),
|
||||||
|
Asset.serial_no.ilike(like),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
rows = query.order_by(Asset.asset_code.asc()).limit(limit).all()
|
||||||
|
rels = _preload_latest_relations(db, [a.id for a in rows])
|
||||||
|
today = effective_today(db)
|
||||||
|
leads = _lead_settings(db)
|
||||||
|
|
||||||
|
items: list[AssetLookupOut] = []
|
||||||
|
for a in rows:
|
||||||
|
d = _derive_asset_fields(a, rels, today, leads)
|
||||||
|
c_obj = d["_contract_obj"]
|
||||||
|
ins_obj = d["_insurance_obj"]
|
||||||
|
if c_obj is not None:
|
||||||
|
c_summary = f"{c_obj.contract_type} ({d['contract_status']}, till {format_date(c_obj.end_date)})"
|
||||||
|
else:
|
||||||
|
c_summary = "No active contract"
|
||||||
|
if ins_obj is not None:
|
||||||
|
ins_summary = f"Policy {ins_obj.policy_no} ({d['insurance_status']}, till {format_date(ins_obj.end_date)})"
|
||||||
|
else:
|
||||||
|
ins_summary = "No policy"
|
||||||
|
|
||||||
|
items.append(
|
||||||
|
AssetLookupOut(
|
||||||
|
id=a.id,
|
||||||
|
asset_code=a.asset_code,
|
||||||
|
serial_no=a.serial_no,
|
||||||
|
name=a.name,
|
||||||
|
category_id=a.category_id,
|
||||||
|
category_name=a.category.name if a.category else None,
|
||||||
|
department_id=a.department_id,
|
||||||
|
department_name=a.department.name if a.department else None,
|
||||||
|
location_id=a.location_id,
|
||||||
|
location_name=a.location.name if a.location else None,
|
||||||
|
supplier_id=a.supplier_id,
|
||||||
|
supplier_name=a.supplier.name if a.supplier else None,
|
||||||
|
status=a.status,
|
||||||
|
criticality=a.criticality,
|
||||||
|
requires_calibration=a.requires_calibration,
|
||||||
|
insurance_applicable=a.insurance_applicable,
|
||||||
|
warranty_status=d["warranty_status"],
|
||||||
|
warranty_end_date=d["warranty_end_date"],
|
||||||
|
contract_status=d["contract_status"],
|
||||||
|
contract_type=d["contract_type"],
|
||||||
|
contract_end_date=d["contract_end_date"],
|
||||||
|
contract_summary=c_summary,
|
||||||
|
insurance_status=d["insurance_status"],
|
||||||
|
insurance_end_date=d["insurance_end_date"],
|
||||||
|
insurance_summary=ins_summary,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
return {"items": items}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("", response_model=AssetListOut)
|
||||||
|
def list_assets(
|
||||||
|
q: Optional[str] = None,
|
||||||
|
department_id: Optional[int] = None,
|
||||||
|
category_id: Optional[int] = None,
|
||||||
|
location_id: Optional[int] = None,
|
||||||
|
supplier_id: Optional[int] = None,
|
||||||
|
status_filter: Optional[str] = Query(None, alias="status"),
|
||||||
|
criticality: Optional[str] = None,
|
||||||
|
warranty_status: Optional[str] = None,
|
||||||
|
contract_status: Optional[str] = None,
|
||||||
|
page: int = Query(1, ge=1),
|
||||||
|
page_size: int = Query(100, ge=0, le=500),
|
||||||
|
sort: str = "id",
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current_user: User = Depends(get_current_user),
|
||||||
|
):
|
||||||
|
query = db.query(Asset).options(
|
||||||
|
joinedload(Asset.category),
|
||||||
|
joinedload(Asset.department),
|
||||||
|
joinedload(Asset.location),
|
||||||
|
joinedload(Asset.supplier),
|
||||||
|
)
|
||||||
|
|
||||||
|
if current_user.role == Role.department_user.value:
|
||||||
|
query = query.filter(Asset.department_id == current_user.department_id)
|
||||||
|
elif department_id is not None:
|
||||||
|
query = query.filter(Asset.department_id == department_id)
|
||||||
|
|
||||||
|
if category_id is not None:
|
||||||
|
query = query.filter(Asset.category_id == category_id)
|
||||||
|
if location_id is not None:
|
||||||
|
query = query.filter(Asset.location_id == location_id)
|
||||||
|
if supplier_id is not None:
|
||||||
|
query = query.filter(Asset.supplier_id == supplier_id)
|
||||||
|
if status_filter:
|
||||||
|
query = query.filter(Asset.status == status_filter)
|
||||||
|
if criticality:
|
||||||
|
query = query.filter(Asset.criticality == criticality)
|
||||||
|
|
||||||
|
if q and q.strip():
|
||||||
|
like = f"%{q.strip()}%"
|
||||||
|
query = query.filter(
|
||||||
|
or_(
|
||||||
|
Asset.asset_code.ilike(like),
|
||||||
|
Asset.name.ilike(like),
|
||||||
|
Asset.serial_no.ilike(like),
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
sort_desc = sort.startswith("-")
|
||||||
|
sort_key = sort.lstrip("-")
|
||||||
|
sort_col_map = {
|
||||||
|
"id": Asset.id,
|
||||||
|
"asset_code": Asset.asset_code,
|
||||||
|
"name": Asset.name,
|
||||||
|
"serial_no": Asset.serial_no,
|
||||||
|
"status": Asset.status,
|
||||||
|
"criticality": Asset.criticality,
|
||||||
|
"purchase_date": Asset.purchase_date,
|
||||||
|
"purchase_value": Asset.purchase_value,
|
||||||
|
}
|
||||||
|
col = sort_col_map.get(sort_key, Asset.id)
|
||||||
|
query = query.order_by(col.desc() if sort_desc else col.asc())
|
||||||
|
|
||||||
|
rows = query.all()
|
||||||
|
rels = _preload_latest_relations(db, [a.id for a in rows])
|
||||||
|
today = effective_today(db)
|
||||||
|
leads = _lead_settings(db)
|
||||||
|
|
||||||
|
out_items = [_to_asset_out(a, rels, today, leads) for a in rows]
|
||||||
|
|
||||||
|
if warranty_status:
|
||||||
|
out_items = [item for item in out_items if item.warranty_status == warranty_status]
|
||||||
|
if contract_status:
|
||||||
|
out_items = [item for item in out_items if item.contract_status == contract_status]
|
||||||
|
|
||||||
|
total = len(out_items)
|
||||||
|
if page_size > 0:
|
||||||
|
start = (page - 1) * page_size
|
||||||
|
out_items = out_items[start : start + page_size]
|
||||||
|
|
||||||
|
return {"items": out_items, "total": total}
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("", response_model=AssetOut, status_code=status.HTTP_201_CREATED)
|
||||||
|
def create_asset(
|
||||||
|
payload: AssetCreate,
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical)),
|
||||||
|
):
|
||||||
|
code_clean = payload.asset_code.strip()
|
||||||
|
if db.query(Asset.id).filter(Asset.asset_code == code_clean).first():
|
||||||
|
raise CodedHTTPException(
|
||||||
|
status_code=status.HTTP_409_CONFLICT,
|
||||||
|
detail="Asset code already exists.",
|
||||||
|
code="DUPLICATE_ASSET_CODE",
|
||||||
|
)
|
||||||
|
|
||||||
|
_validate_asset_fks(
|
||||||
|
db,
|
||||||
|
category_id=payload.category_id,
|
||||||
|
department_id=payload.department_id,
|
||||||
|
location_id=payload.location_id,
|
||||||
|
supplier_id=payload.supplier_id,
|
||||||
|
)
|
||||||
|
|
||||||
|
asset = Asset(
|
||||||
|
asset_code=code_clean,
|
||||||
|
serial_no=payload.serial_no.strip(),
|
||||||
|
name=payload.name.strip(),
|
||||||
|
category_id=payload.category_id,
|
||||||
|
department_id=payload.department_id,
|
||||||
|
location_id=payload.location_id,
|
||||||
|
supplier_id=payload.supplier_id,
|
||||||
|
purchase_value=payload.purchase_value,
|
||||||
|
purchase_date=payload.purchase_date,
|
||||||
|
installation_date=payload.installation_date,
|
||||||
|
status=payload.status,
|
||||||
|
criticality=payload.criticality,
|
||||||
|
requires_calibration=payload.requires_calibration,
|
||||||
|
insurance_applicable=payload.insurance_applicable,
|
||||||
|
remarks=payload.remarks,
|
||||||
|
created_by_id=current_user.id,
|
||||||
|
updated_by_id=current_user.id,
|
||||||
|
)
|
||||||
|
db.add(asset)
|
||||||
|
try:
|
||||||
|
db.flush()
|
||||||
|
except IntegrityError:
|
||||||
|
db.rollback()
|
||||||
|
raise CodedHTTPException(
|
||||||
|
status_code=status.HTTP_409_CONFLICT,
|
||||||
|
detail="Asset code already exists.",
|
||||||
|
code="DUPLICATE_ASSET_CODE",
|
||||||
|
)
|
||||||
|
|
||||||
|
log_audit(
|
||||||
|
db,
|
||||||
|
entity_type="asset",
|
||||||
|
entity_id=asset.id,
|
||||||
|
action="create",
|
||||||
|
changes={"asset_code": asset.asset_code, "name": asset.name, "department_id": asset.department_id},
|
||||||
|
user_id=current_user.id,
|
||||||
|
)
|
||||||
|
db.commit()
|
||||||
|
|
||||||
|
loaded = _load_asset_with_joins(db, asset.id)
|
||||||
|
rels = _preload_latest_relations(db, [asset.id])
|
||||||
|
return _to_asset_out(loaded, rels, effective_today(db), _lead_settings(db))
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{asset_id}", response_model=AssetOut)
|
||||||
|
def get_asset(
|
||||||
|
asset_id: int,
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current_user: User = Depends(get_current_user),
|
||||||
|
):
|
||||||
|
asset = _load_asset_with_joins(db, asset_id)
|
||||||
|
if asset is None:
|
||||||
|
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Asset not found.")
|
||||||
|
if current_user.role == Role.department_user.value and asset.department_id != current_user.department_id:
|
||||||
|
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Access denied for another department's asset.")
|
||||||
|
|
||||||
|
rels = _preload_latest_relations(db, [asset.id])
|
||||||
|
return _to_asset_out(asset, rels, effective_today(db), _lead_settings(db))
|
||||||
|
|
||||||
|
|
||||||
|
@router.patch("/{asset_id}", response_model=AssetOut)
|
||||||
|
def update_asset(
|
||||||
|
asset_id: int,
|
||||||
|
payload: AssetUpdate,
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.coordinator)),
|
||||||
|
):
|
||||||
|
asset = _load_asset_with_joins(db, asset_id)
|
||||||
|
if asset is None:
|
||||||
|
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Asset not found.")
|
||||||
|
|
||||||
|
data = payload.model_dump(exclude_unset=True)
|
||||||
|
if current_user.role == Role.coordinator.value:
|
||||||
|
disallowed = set(data.keys()) - COORDINATOR_ALLOWED_FIELDS
|
||||||
|
if disallowed:
|
||||||
|
raise CodedHTTPException(
|
||||||
|
status_code=status.HTTP_403_FORBIDDEN,
|
||||||
|
detail="Coordinators can only edit contract-related asset fields.",
|
||||||
|
code="FORBIDDEN",
|
||||||
|
)
|
||||||
|
|
||||||
|
if "asset_code" in data and data["asset_code"] is not None:
|
||||||
|
new_code = data["asset_code"].strip()
|
||||||
|
existing = db.query(Asset.id).filter(Asset.asset_code == new_code, Asset.id != asset.id).first()
|
||||||
|
if existing:
|
||||||
|
raise CodedHTTPException(
|
||||||
|
status_code=status.HTTP_409_CONFLICT,
|
||||||
|
detail="Asset code already exists.",
|
||||||
|
code="DUPLICATE_ASSET_CODE",
|
||||||
|
)
|
||||||
|
data["asset_code"] = new_code
|
||||||
|
|
||||||
|
if "serial_no" in data and data["serial_no"] is not None:
|
||||||
|
data["serial_no"] = data["serial_no"].strip()
|
||||||
|
if "name" in data and data["name"] is not None:
|
||||||
|
data["name"] = data["name"].strip()
|
||||||
|
|
||||||
|
_validate_asset_fks(
|
||||||
|
db,
|
||||||
|
category_id=data.get("category_id"),
|
||||||
|
department_id=data.get("department_id"),
|
||||||
|
location_id=data.get("location_id"),
|
||||||
|
supplier_id=data.get("supplier_id"),
|
||||||
|
)
|
||||||
|
|
||||||
|
changes: dict[str, dict[str, Any]] = {}
|
||||||
|
for k, v in data.items():
|
||||||
|
old_val = getattr(asset, k)
|
||||||
|
if old_val != v:
|
||||||
|
changes[k] = {"from": old_val, "to": v}
|
||||||
|
setattr(asset, k, v)
|
||||||
|
asset.updated_by_id = current_user.id
|
||||||
|
|
||||||
|
if changes:
|
||||||
|
log_audit(
|
||||||
|
db,
|
||||||
|
entity_type="asset",
|
||||||
|
entity_id=asset.id,
|
||||||
|
action="update",
|
||||||
|
changes=changes,
|
||||||
|
user_id=current_user.id,
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
db.commit()
|
||||||
|
except IntegrityError:
|
||||||
|
db.rollback()
|
||||||
|
raise CodedHTTPException(
|
||||||
|
status_code=status.HTTP_409_CONFLICT,
|
||||||
|
detail="Asset code already exists.",
|
||||||
|
code="DUPLICATE_ASSET_CODE",
|
||||||
|
)
|
||||||
|
|
||||||
|
loaded = _load_asset_with_joins(db, asset.id)
|
||||||
|
rels = _preload_latest_relations(db, [asset.id])
|
||||||
|
return _to_asset_out(loaded, rels, effective_today(db), _lead_settings(db))
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{asset_id}/overview", response_model=AssetOverviewOut)
|
||||||
|
def get_asset_overview(
|
||||||
|
asset_id: int,
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current_user: User = Depends(get_current_user),
|
||||||
|
):
|
||||||
|
asset = _load_asset_with_joins(db, asset_id)
|
||||||
|
if asset is None:
|
||||||
|
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Asset not found.")
|
||||||
|
if current_user.role == Role.department_user.value and asset.department_id != current_user.department_id:
|
||||||
|
raise HTTPException(status_code=status.HTTP_403_FORBIDDEN, detail="Access denied for another department's asset.")
|
||||||
|
|
||||||
|
today = effective_today(db)
|
||||||
|
leads = _lead_settings(db)
|
||||||
|
rels = _preload_latest_relations(db, [asset.id])
|
||||||
|
asset_out = _to_asset_out(asset, rels, today, leads)
|
||||||
|
|
||||||
|
warranties_rows = (
|
||||||
|
db.query(Warranty)
|
||||||
|
.options(joinedload(Warranty.provider))
|
||||||
|
.filter(Warranty.asset_id == asset.id)
|
||||||
|
.order_by(Warranty.end_date.desc(), Warranty.id.desc())
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
warranties_out = []
|
||||||
|
for w in warranties_rows:
|
||||||
|
st, sev = coverage_status(w.start_date, w.end_date, today, leads["warranty"], leads["red"])
|
||||||
|
warranties_out.append(
|
||||||
|
WarrantySummaryOut(
|
||||||
|
id=w.id,
|
||||||
|
asset_id=w.asset_id,
|
||||||
|
duration_months=w.duration_months,
|
||||||
|
start_date=w.start_date,
|
||||||
|
end_date=w.end_date,
|
||||||
|
provider_id=w.provider_id,
|
||||||
|
provider_name=w.provider.name if w.provider else None,
|
||||||
|
status=st,
|
||||||
|
severity=sev,
|
||||||
|
remarks=w.remarks,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
contracts_rows = (
|
||||||
|
db.query(Contract)
|
||||||
|
.options(joinedload(Contract.provider))
|
||||||
|
.filter(Contract.asset_id == asset.id)
|
||||||
|
.order_by(Contract.is_superseded.asc(), Contract.end_date.desc(), Contract.id.desc())
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
contracts_out = []
|
||||||
|
for c in contracts_rows:
|
||||||
|
if c.is_superseded:
|
||||||
|
st, sev = "superseded", "none"
|
||||||
|
else:
|
||||||
|
st, sev = coverage_status(c.start_date, c.end_date, today, leads["contract"], leads["red"])
|
||||||
|
contracts_out.append(
|
||||||
|
ContractSummaryOut(
|
||||||
|
id=c.id,
|
||||||
|
asset_id=c.asset_id,
|
||||||
|
contract_type=c.contract_type,
|
||||||
|
provider_id=c.provider_id,
|
||||||
|
provider_name=c.provider.name if c.provider else None,
|
||||||
|
start_date=c.start_date,
|
||||||
|
end_date=c.end_date,
|
||||||
|
coverage_period_text=c.coverage_period_text,
|
||||||
|
renewed_from_id=c.renewed_from_id,
|
||||||
|
is_superseded=c.is_superseded,
|
||||||
|
status=st,
|
||||||
|
severity=sev,
|
||||||
|
remarks=c.remarks,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
insurance_rows = (
|
||||||
|
db.query(InsurancePolicy)
|
||||||
|
.options(joinedload(InsurancePolicy.insurer))
|
||||||
|
.filter(InsurancePolicy.asset_id == asset.id)
|
||||||
|
.order_by(InsurancePolicy.end_date.desc(), InsurancePolicy.id.desc())
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
insurance_out = []
|
||||||
|
for ins in insurance_rows:
|
||||||
|
st, sev = coverage_status(ins.start_date, ins.end_date, today, leads["insurance"], leads["red"])
|
||||||
|
insurance_out.append(
|
||||||
|
InsuranceSummaryOut(
|
||||||
|
id=ins.id,
|
||||||
|
asset_id=ins.asset_id,
|
||||||
|
insurer_id=ins.insurer_id,
|
||||||
|
insurer_name=ins.insurer.name if ins.insurer else None,
|
||||||
|
policy_no=ins.policy_no,
|
||||||
|
start_date=ins.start_date,
|
||||||
|
end_date=ins.end_date,
|
||||||
|
coverage_amount=ins.coverage_amount,
|
||||||
|
status=st,
|
||||||
|
severity=sev,
|
||||||
|
remarks=ins.remarks,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
cal_plan_row = (
|
||||||
|
db.query(CalibrationPlan)
|
||||||
|
.options(joinedload(CalibrationPlan.agency))
|
||||||
|
.filter(CalibrationPlan.asset_id == asset.id)
|
||||||
|
.first()
|
||||||
|
)
|
||||||
|
cal_plan_out = (
|
||||||
|
CalibrationPlanSummaryOut(
|
||||||
|
id=cal_plan_row.id,
|
||||||
|
asset_id=cal_plan_row.asset_id,
|
||||||
|
frequency_months=cal_plan_row.frequency_months,
|
||||||
|
calibrations_per_year=cal_plan_row.calibrations_per_year,
|
||||||
|
agency_id=cal_plan_row.agency_id,
|
||||||
|
agency_name=cal_plan_row.agency.name if cal_plan_row.agency else None,
|
||||||
|
approved_by_id=cal_plan_row.approved_by_id,
|
||||||
|
approved_on=cal_plan_row.approved_on,
|
||||||
|
next_due_date=cal_plan_row.next_due_date,
|
||||||
|
is_active=cal_plan_row.is_active,
|
||||||
|
)
|
||||||
|
if cal_plan_row
|
||||||
|
else None
|
||||||
|
)
|
||||||
|
|
||||||
|
cal_records_rows = (
|
||||||
|
db.query(CalibrationRecord)
|
||||||
|
.options(joinedload(CalibrationRecord.agency))
|
||||||
|
.filter(CalibrationRecord.asset_id == asset.id)
|
||||||
|
.order_by(CalibrationRecord.due_date.desc(), CalibrationRecord.id.desc())
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
cal_records_out = []
|
||||||
|
for rec in cal_records_rows:
|
||||||
|
st, sev = compute_schedule_status(rec.due_date, rec.status, today, leads["calibration"], leads["red"])
|
||||||
|
cal_records_out.append(
|
||||||
|
CalibrationRecordSummaryOut(
|
||||||
|
id=rec.id,
|
||||||
|
asset_id=rec.asset_id,
|
||||||
|
plan_id=rec.plan_id,
|
||||||
|
due_date=rec.due_date,
|
||||||
|
completed_date=rec.completed_date,
|
||||||
|
agency_id=rec.agency_id,
|
||||||
|
agency_name=rec.agency.name if rec.agency else None,
|
||||||
|
certificate_no=rec.certificate_no,
|
||||||
|
remarks=rec.remarks,
|
||||||
|
status=st,
|
||||||
|
severity=sev,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
pm_sched_rows = (
|
||||||
|
db.query(PMSchedule)
|
||||||
|
.options(joinedload(PMSchedule.provider))
|
||||||
|
.filter(PMSchedule.asset_id == asset.id)
|
||||||
|
.order_by(PMSchedule.id.desc())
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
pm_sched_out = [
|
||||||
|
PMScheduleSummaryOut(
|
||||||
|
id=s.id,
|
||||||
|
asset_id=s.asset_id,
|
||||||
|
service_mode=s.service_mode,
|
||||||
|
frequency_months=s.frequency_months,
|
||||||
|
responsible_team=s.responsible_team,
|
||||||
|
provider_id=s.provider_id,
|
||||||
|
provider_name=s.provider.name if s.provider else None,
|
||||||
|
contract_id=s.contract_id,
|
||||||
|
next_planned_date=s.next_planned_date,
|
||||||
|
is_active=s.is_active,
|
||||||
|
)
|
||||||
|
for s in pm_sched_rows
|
||||||
|
]
|
||||||
|
|
||||||
|
pm_rec_rows = (
|
||||||
|
db.query(PMRecord)
|
||||||
|
.filter(PMRecord.asset_id == asset.id)
|
||||||
|
.order_by(PMRecord.planned_date.desc(), PMRecord.id.desc())
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
pm_rec_out = []
|
||||||
|
for r in pm_rec_rows:
|
||||||
|
st, sev = compute_schedule_status(r.planned_date, r.status, today, leads["pm"], leads["red"])
|
||||||
|
pm_rec_out.append(
|
||||||
|
PMRecordSummaryOut(
|
||||||
|
id=r.id,
|
||||||
|
schedule_id=r.schedule_id,
|
||||||
|
asset_id=r.asset_id,
|
||||||
|
planned_date=r.planned_date,
|
||||||
|
completed_date=r.completed_date,
|
||||||
|
status=st,
|
||||||
|
severity=sev,
|
||||||
|
service_details=r.service_details,
|
||||||
|
remarks=r.remarks,
|
||||||
|
rescheduled_to=r.rescheduled_to,
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
complaint_rows = (
|
||||||
|
db.query(Complaint)
|
||||||
|
.filter(Complaint.asset_id == asset.id)
|
||||||
|
.order_by(Complaint.registered_at.desc(), Complaint.id.desc())
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
complaints_out = [
|
||||||
|
ComplaintSummaryOut(
|
||||||
|
id=comp.id,
|
||||||
|
complaint_no=comp.complaint_no,
|
||||||
|
asset_id=comp.asset_id,
|
||||||
|
description=comp.description,
|
||||||
|
priority=comp.priority,
|
||||||
|
call_status=comp.call_status,
|
||||||
|
registered_at=comp.registered_at,
|
||||||
|
closed_at=comp.closed_at,
|
||||||
|
)
|
||||||
|
for comp in complaint_rows
|
||||||
|
]
|
||||||
|
|
||||||
|
att_rows = (
|
||||||
|
db.query(Attachment)
|
||||||
|
.filter(Attachment.entity_type == "asset", Attachment.entity_id == asset.id)
|
||||||
|
.order_by(Attachment.uploaded_at.desc(), Attachment.id.desc())
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
uploader_ids = {a.uploaded_by_id for a in att_rows}
|
||||||
|
uploader_names = {}
|
||||||
|
if uploader_ids:
|
||||||
|
uploader_names = {
|
||||||
|
u.id: u.name
|
||||||
|
for u in db.query(User.id, User.name).filter(User.id.in_(uploader_ids)).all()
|
||||||
|
}
|
||||||
|
attachments_out = [
|
||||||
|
AttachmentSummaryOut(
|
||||||
|
id=a.id,
|
||||||
|
entity_type=a.entity_type,
|
||||||
|
entity_id=a.entity_id,
|
||||||
|
original_name=a.original_name,
|
||||||
|
mime_type=a.mime_type,
|
||||||
|
size_bytes=a.size_bytes,
|
||||||
|
uploaded_by_id=a.uploaded_by_id,
|
||||||
|
uploaded_by_name=uploader_names.get(a.uploaded_by_id),
|
||||||
|
uploaded_at=a.uploaded_at,
|
||||||
|
)
|
||||||
|
for a in att_rows
|
||||||
|
]
|
||||||
|
|
||||||
|
return AssetOverviewOut(
|
||||||
|
asset=asset_out,
|
||||||
|
warranties=warranties_out,
|
||||||
|
contracts=contracts_out,
|
||||||
|
insurance_policies=insurance_out,
|
||||||
|
calibration_plan=cal_plan_out,
|
||||||
|
calibration_records=cal_records_out,
|
||||||
|
pm_schedules=pm_sched_out,
|
||||||
|
pm_records=pm_rec_out,
|
||||||
|
complaints=complaints_out,
|
||||||
|
attachments=attachments_out,
|
||||||
|
)
|
||||||
@@ -0,0 +1,104 @@
|
|||||||
|
from pathlib import Path
|
||||||
|
from fastapi import APIRouter, Depends, File, Form, Query, Response, UploadFile, status
|
||||||
|
from fastapi.responses import FileResponse
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
|
||||||
|
from ..core.config import settings
|
||||||
|
from ..core.db import get_db
|
||||||
|
from ..core.deps import get_current_user
|
||||||
|
from ..core.exceptions import CodedHTTPException
|
||||||
|
from ..models import Attachment, User
|
||||||
|
from ..schemas.attachments import AttachmentListOut, AttachmentOut
|
||||||
|
from ..services.attachment_service import (
|
||||||
|
assert_entity_visible,
|
||||||
|
delete_attachment,
|
||||||
|
save_attachment,
|
||||||
|
)
|
||||||
|
|
||||||
|
router = APIRouter(prefix="/attachments", tags=["attachments"])
|
||||||
|
|
||||||
|
|
||||||
|
def _to_out(att: Attachment, user_names: dict[int, str]) -> AttachmentOut:
|
||||||
|
return AttachmentOut(
|
||||||
|
id=att.id,
|
||||||
|
entity_type=att.entity_type,
|
||||||
|
entity_id=att.entity_id,
|
||||||
|
original_name=att.original_name,
|
||||||
|
mime_type=att.mime_type,
|
||||||
|
size_bytes=att.size_bytes,
|
||||||
|
uploaded_by_id=att.uploaded_by_id,
|
||||||
|
uploaded_by_name=user_names.get(att.uploaded_by_id),
|
||||||
|
uploaded_at=att.uploaded_at,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.post("", response_model=AttachmentOut, status_code=status.HTTP_201_CREATED)
|
||||||
|
def upload_attachment(
|
||||||
|
entity_type: str = Form(...),
|
||||||
|
entity_id: int = Form(...),
|
||||||
|
file: UploadFile = File(...),
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current_user: User = Depends(get_current_user),
|
||||||
|
):
|
||||||
|
att = save_attachment(db, current_user, entity_type, entity_id, file)
|
||||||
|
return _to_out(att, {current_user.id: current_user.name})
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("", response_model=AttachmentListOut)
|
||||||
|
def list_attachments(
|
||||||
|
entity_type: str = Query(...),
|
||||||
|
entity_id: int = Query(...),
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current_user: User = Depends(get_current_user),
|
||||||
|
):
|
||||||
|
assert_entity_visible(db, current_user, entity_type, entity_id)
|
||||||
|
rows = (
|
||||||
|
db.query(Attachment)
|
||||||
|
.filter(Attachment.entity_type == entity_type, Attachment.entity_id == entity_id)
|
||||||
|
.order_by(Attachment.uploaded_at.desc(), Attachment.id.desc())
|
||||||
|
.all()
|
||||||
|
)
|
||||||
|
user_ids = {r.uploaded_by_id for r in rows}
|
||||||
|
user_names = {}
|
||||||
|
if user_ids:
|
||||||
|
user_names = {
|
||||||
|
u.id: u.name
|
||||||
|
for u in db.query(User.id, User.name).filter(User.id.in_(user_ids)).all()
|
||||||
|
}
|
||||||
|
return {
|
||||||
|
"items": [_to_out(r, user_names) for r in rows],
|
||||||
|
"total": len(rows),
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
@router.get("/{attachment_id}/download")
|
||||||
|
def download_attachment(
|
||||||
|
attachment_id: int,
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current_user: User = Depends(get_current_user),
|
||||||
|
):
|
||||||
|
att = db.query(Attachment).filter(Attachment.id == attachment_id).first()
|
||||||
|
if att is None:
|
||||||
|
raise CodedHTTPException(status_code=404, detail="Attachment not found.", code="NOT_FOUND")
|
||||||
|
|
||||||
|
assert_entity_visible(db, current_user, att.entity_type, att.entity_id)
|
||||||
|
|
||||||
|
file_path = Path(settings.UPLOAD_DIR) / att.stored_name
|
||||||
|
if not file_path.is_file():
|
||||||
|
raise CodedHTTPException(status_code=404, detail="Attachment file missing on disk.", code="FILE_NOT_FOUND")
|
||||||
|
|
||||||
|
return FileResponse(
|
||||||
|
path=file_path,
|
||||||
|
media_type=att.mime_type,
|
||||||
|
filename=att.original_name,
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
@router.delete("/{attachment_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||||
|
def remove_attachment(
|
||||||
|
attachment_id: int,
|
||||||
|
db: Session = Depends(get_db),
|
||||||
|
current_user: User = Depends(get_current_user),
|
||||||
|
):
|
||||||
|
delete_attachment(db, current_user, attachment_id)
|
||||||
|
return Response(status_code=status.HTTP_204_NO_CONTENT)
|
||||||
@@ -1,3 +1,13 @@
|
|||||||
|
from .assets import (
|
||||||
|
AssetCreate,
|
||||||
|
AssetListOut,
|
||||||
|
AssetLookupListOut,
|
||||||
|
AssetLookupOut,
|
||||||
|
AssetOut,
|
||||||
|
AssetOverviewOut,
|
||||||
|
AssetUpdate,
|
||||||
|
)
|
||||||
|
from .attachments import AttachmentListOut, AttachmentOut
|
||||||
from .auth import LoginRequest, TokenResponse, UserOut
|
from .auth import LoginRequest, TokenResponse, UserOut
|
||||||
from .masters import (
|
from .masters import (
|
||||||
CategoryCreate,
|
CategoryCreate,
|
||||||
@@ -21,6 +31,15 @@ from .masters import (
|
|||||||
from .settings import DemoDateIn, DemoDateOut, SettingItemOut, SettingsListOut, SettingsUpdateIn
|
from .settings import DemoDateIn, DemoDateOut, SettingItemOut, SettingsListOut, SettingsUpdateIn
|
||||||
|
|
||||||
__all__ = [
|
__all__ = [
|
||||||
|
"AssetCreate",
|
||||||
|
"AssetListOut",
|
||||||
|
"AssetLookupListOut",
|
||||||
|
"AssetLookupOut",
|
||||||
|
"AssetOut",
|
||||||
|
"AssetOverviewOut",
|
||||||
|
"AssetUpdate",
|
||||||
|
"AttachmentListOut",
|
||||||
|
"AttachmentOut",
|
||||||
"LoginRequest",
|
"LoginRequest",
|
||||||
"TokenResponse",
|
"TokenResponse",
|
||||||
"UserOut",
|
"UserOut",
|
||||||
|
|||||||
@@ -0,0 +1,250 @@
|
|||||||
|
from datetime import date, datetime
|
||||||
|
from typing import Literal, Optional
|
||||||
|
from pydantic import BaseModel, ConfigDict, Field
|
||||||
|
|
||||||
|
AssetStatus = Literal["in_service", "under_repair", "condemned", "out_of_service"]
|
||||||
|
AssetCriticality = Literal["critical", "non_critical"]
|
||||||
|
|
||||||
|
|
||||||
|
class AssetCreate(BaseModel):
|
||||||
|
asset_code: str = Field(..., min_length=1, max_length=60)
|
||||||
|
serial_no: str = Field(..., min_length=1, max_length=100)
|
||||||
|
name: str = Field(..., min_length=1, max_length=200)
|
||||||
|
category_id: int
|
||||||
|
department_id: int
|
||||||
|
location_id: int
|
||||||
|
supplier_id: Optional[int] = None
|
||||||
|
purchase_value: Optional[float] = Field(None, ge=0)
|
||||||
|
purchase_date: Optional[date] = None
|
||||||
|
installation_date: Optional[date] = None
|
||||||
|
status: AssetStatus = "in_service"
|
||||||
|
criticality: AssetCriticality = "non_critical"
|
||||||
|
requires_calibration: bool = False
|
||||||
|
insurance_applicable: bool = False
|
||||||
|
remarks: Optional[str] = None
|
||||||
|
|
||||||
|
|
||||||
|
class AssetUpdate(BaseModel):
|
||||||
|
asset_code: Optional[str] = Field(None, min_length=1, max_length=60)
|
||||||
|
serial_no: Optional[str] = Field(None, min_length=1, max_length=100)
|
||||||
|
name: Optional[str] = Field(None, min_length=1, max_length=200)
|
||||||
|
category_id: Optional[int] = None
|
||||||
|
department_id: Optional[int] = None
|
||||||
|
location_id: Optional[int] = None
|
||||||
|
supplier_id: Optional[int] = None
|
||||||
|
purchase_value: Optional[float] = Field(None, ge=0)
|
||||||
|
purchase_date: Optional[date] = None
|
||||||
|
installation_date: Optional[date] = None
|
||||||
|
status: Optional[AssetStatus] = None
|
||||||
|
criticality: Optional[AssetCriticality] = None
|
||||||
|
requires_calibration: Optional[bool] = None
|
||||||
|
insurance_applicable: Optional[bool] = None
|
||||||
|
remarks: Optional[str] = None
|
||||||
|
|
||||||
|
|
||||||
|
class AssetOut(BaseModel):
|
||||||
|
model_config = ConfigDict(from_attributes=True)
|
||||||
|
|
||||||
|
id: int
|
||||||
|
asset_code: str
|
||||||
|
serial_no: str
|
||||||
|
name: str
|
||||||
|
category_id: int
|
||||||
|
category_name: Optional[str] = None
|
||||||
|
department_id: int
|
||||||
|
department_name: Optional[str] = None
|
||||||
|
location_id: int
|
||||||
|
location_name: Optional[str] = None
|
||||||
|
supplier_id: Optional[int] = None
|
||||||
|
supplier_name: Optional[str] = None
|
||||||
|
purchase_value: Optional[float] = None
|
||||||
|
purchase_date: Optional[date] = None
|
||||||
|
installation_date: Optional[date] = None
|
||||||
|
status: str
|
||||||
|
criticality: str
|
||||||
|
requires_calibration: bool
|
||||||
|
insurance_applicable: bool
|
||||||
|
remarks: Optional[str] = None
|
||||||
|
warranty_status: str = "none"
|
||||||
|
warranty_end_date: Optional[date] = None
|
||||||
|
warranty_severity: str = "none"
|
||||||
|
contract_status: str = "none"
|
||||||
|
contract_type: Optional[str] = None
|
||||||
|
contract_end_date: Optional[date] = None
|
||||||
|
contract_severity: str = "none"
|
||||||
|
calibration_status: str = "none"
|
||||||
|
calibration_due_date: Optional[date] = None
|
||||||
|
calibration_severity: str = "none"
|
||||||
|
insurance_status: str = "none"
|
||||||
|
insurance_end_date: Optional[date] = None
|
||||||
|
created_at: datetime
|
||||||
|
updated_at: datetime
|
||||||
|
|
||||||
|
|
||||||
|
class AssetListOut(BaseModel):
|
||||||
|
items: list[AssetOut]
|
||||||
|
total: int
|
||||||
|
|
||||||
|
|
||||||
|
class AssetLookupOut(BaseModel):
|
||||||
|
id: int
|
||||||
|
asset_code: str
|
||||||
|
serial_no: str
|
||||||
|
name: str
|
||||||
|
category_id: int
|
||||||
|
category_name: Optional[str] = None
|
||||||
|
department_id: int
|
||||||
|
department_name: Optional[str] = None
|
||||||
|
location_id: int
|
||||||
|
location_name: Optional[str] = None
|
||||||
|
supplier_id: Optional[int] = None
|
||||||
|
supplier_name: Optional[str] = None
|
||||||
|
status: str
|
||||||
|
criticality: str
|
||||||
|
requires_calibration: bool
|
||||||
|
insurance_applicable: bool
|
||||||
|
warranty_status: str = "none"
|
||||||
|
warranty_end_date: Optional[date] = None
|
||||||
|
contract_status: str = "none"
|
||||||
|
contract_type: Optional[str] = None
|
||||||
|
contract_end_date: Optional[date] = None
|
||||||
|
contract_summary: str = "No active contract"
|
||||||
|
insurance_status: str = "none"
|
||||||
|
insurance_end_date: Optional[date] = None
|
||||||
|
insurance_summary: str = "No policy"
|
||||||
|
|
||||||
|
|
||||||
|
class AssetLookupListOut(BaseModel):
|
||||||
|
items: list[AssetLookupOut]
|
||||||
|
|
||||||
|
|
||||||
|
class WarrantySummaryOut(BaseModel):
|
||||||
|
id: int
|
||||||
|
asset_id: int
|
||||||
|
duration_months: int
|
||||||
|
start_date: date
|
||||||
|
end_date: date
|
||||||
|
provider_id: Optional[int] = None
|
||||||
|
provider_name: Optional[str] = None
|
||||||
|
status: str
|
||||||
|
severity: str
|
||||||
|
remarks: Optional[str] = None
|
||||||
|
|
||||||
|
|
||||||
|
class ContractSummaryOut(BaseModel):
|
||||||
|
id: int
|
||||||
|
asset_id: int
|
||||||
|
contract_type: str
|
||||||
|
provider_id: int
|
||||||
|
provider_name: Optional[str] = None
|
||||||
|
start_date: date
|
||||||
|
end_date: date
|
||||||
|
coverage_period_text: Optional[str] = None
|
||||||
|
renewed_from_id: Optional[int] = None
|
||||||
|
is_superseded: bool
|
||||||
|
status: str
|
||||||
|
severity: str
|
||||||
|
remarks: Optional[str] = None
|
||||||
|
|
||||||
|
|
||||||
|
class InsuranceSummaryOut(BaseModel):
|
||||||
|
id: int
|
||||||
|
asset_id: int
|
||||||
|
insurer_id: int
|
||||||
|
insurer_name: Optional[str] = None
|
||||||
|
policy_no: str
|
||||||
|
start_date: date
|
||||||
|
end_date: date
|
||||||
|
coverage_amount: Optional[float] = None
|
||||||
|
status: str
|
||||||
|
severity: str
|
||||||
|
remarks: Optional[str] = None
|
||||||
|
|
||||||
|
|
||||||
|
class CalibrationPlanSummaryOut(BaseModel):
|
||||||
|
id: int
|
||||||
|
asset_id: int
|
||||||
|
frequency_months: int
|
||||||
|
calibrations_per_year: int
|
||||||
|
agency_id: Optional[int] = None
|
||||||
|
agency_name: Optional[str] = None
|
||||||
|
approved_by_id: Optional[int] = None
|
||||||
|
approved_on: Optional[date] = None
|
||||||
|
next_due_date: date
|
||||||
|
is_active: bool
|
||||||
|
|
||||||
|
|
||||||
|
class CalibrationRecordSummaryOut(BaseModel):
|
||||||
|
id: int
|
||||||
|
asset_id: int
|
||||||
|
plan_id: int
|
||||||
|
due_date: date
|
||||||
|
completed_date: Optional[date] = None
|
||||||
|
agency_id: Optional[int] = None
|
||||||
|
agency_name: Optional[str] = None
|
||||||
|
certificate_no: Optional[str] = None
|
||||||
|
remarks: Optional[str] = None
|
||||||
|
status: str
|
||||||
|
severity: str
|
||||||
|
|
||||||
|
|
||||||
|
class PMScheduleSummaryOut(BaseModel):
|
||||||
|
id: int
|
||||||
|
asset_id: int
|
||||||
|
service_mode: str
|
||||||
|
frequency_months: int
|
||||||
|
responsible_team: Optional[str] = None
|
||||||
|
provider_id: Optional[int] = None
|
||||||
|
provider_name: Optional[str] = None
|
||||||
|
contract_id: Optional[int] = None
|
||||||
|
next_planned_date: date
|
||||||
|
is_active: bool
|
||||||
|
|
||||||
|
|
||||||
|
class PMRecordSummaryOut(BaseModel):
|
||||||
|
id: int
|
||||||
|
schedule_id: int
|
||||||
|
asset_id: int
|
||||||
|
planned_date: date
|
||||||
|
completed_date: Optional[date] = None
|
||||||
|
status: str
|
||||||
|
severity: str
|
||||||
|
service_details: Optional[str] = None
|
||||||
|
remarks: Optional[str] = None
|
||||||
|
rescheduled_to: Optional[date] = None
|
||||||
|
|
||||||
|
|
||||||
|
class ComplaintSummaryOut(BaseModel):
|
||||||
|
id: int
|
||||||
|
complaint_no: str
|
||||||
|
asset_id: int
|
||||||
|
description: str
|
||||||
|
priority: str
|
||||||
|
call_status: str
|
||||||
|
registered_at: datetime
|
||||||
|
closed_at: Optional[datetime] = None
|
||||||
|
|
||||||
|
|
||||||
|
class AttachmentSummaryOut(BaseModel):
|
||||||
|
id: int
|
||||||
|
entity_type: str
|
||||||
|
entity_id: int
|
||||||
|
original_name: str
|
||||||
|
mime_type: str
|
||||||
|
size_bytes: int
|
||||||
|
uploaded_by_id: int
|
||||||
|
uploaded_by_name: Optional[str] = None
|
||||||
|
uploaded_at: datetime
|
||||||
|
|
||||||
|
|
||||||
|
class AssetOverviewOut(BaseModel):
|
||||||
|
asset: AssetOut
|
||||||
|
warranties: list[WarrantySummaryOut]
|
||||||
|
contracts: list[ContractSummaryOut]
|
||||||
|
insurance_policies: list[InsuranceSummaryOut]
|
||||||
|
calibration_plan: Optional[CalibrationPlanSummaryOut] = None
|
||||||
|
calibration_records: list[CalibrationRecordSummaryOut]
|
||||||
|
pm_schedules: list[PMScheduleSummaryOut]
|
||||||
|
pm_records: list[PMRecordSummaryOut]
|
||||||
|
complaints: list[ComplaintSummaryOut]
|
||||||
|
attachments: list[AttachmentSummaryOut]
|
||||||
@@ -0,0 +1,22 @@
|
|||||||
|
from datetime import datetime
|
||||||
|
from typing import Optional
|
||||||
|
from pydantic import BaseModel, ConfigDict
|
||||||
|
|
||||||
|
|
||||||
|
class AttachmentOut(BaseModel):
|
||||||
|
model_config = ConfigDict(from_attributes=True)
|
||||||
|
|
||||||
|
id: int
|
||||||
|
entity_type: str
|
||||||
|
entity_id: int
|
||||||
|
original_name: str
|
||||||
|
mime_type: str
|
||||||
|
size_bytes: int
|
||||||
|
uploaded_by_id: int
|
||||||
|
uploaded_by_name: Optional[str] = None
|
||||||
|
uploaded_at: datetime
|
||||||
|
|
||||||
|
|
||||||
|
class AttachmentListOut(BaseModel):
|
||||||
|
items: list[AttachmentOut]
|
||||||
|
total: int
|
||||||
@@ -0,0 +1,304 @@
|
|||||||
|
from pathlib import Path
|
||||||
|
from uuid import uuid4
|
||||||
|
from fastapi import UploadFile
|
||||||
|
from sqlalchemy.orm import Session, joinedload
|
||||||
|
|
||||||
|
from ..core.config import settings
|
||||||
|
from ..core.exceptions import CodedHTTPException
|
||||||
|
from ..core.time_utils import utc_now
|
||||||
|
from ..models import (
|
||||||
|
Asset,
|
||||||
|
Attachment,
|
||||||
|
CalibrationRecord,
|
||||||
|
Complaint,
|
||||||
|
Contract,
|
||||||
|
DemoEquipment,
|
||||||
|
InsurancePolicy,
|
||||||
|
User,
|
||||||
|
Warranty,
|
||||||
|
)
|
||||||
|
from ..services.audit import log_audit
|
||||||
|
from ..services.permissions import Role
|
||||||
|
|
||||||
|
ALLOWED_ENTITY_TYPES: set[str] = {
|
||||||
|
"complaint",
|
||||||
|
"contract",
|
||||||
|
"calibration_record",
|
||||||
|
"insurance",
|
||||||
|
"demo_equipment",
|
||||||
|
"asset",
|
||||||
|
"warranty",
|
||||||
|
}
|
||||||
|
|
||||||
|
EXT_TO_MIME: dict[str, str] = {
|
||||||
|
".jpg": "image/jpeg",
|
||||||
|
".jpeg": "image/jpeg",
|
||||||
|
".png": "image/png",
|
||||||
|
".pdf": "application/pdf",
|
||||||
|
}
|
||||||
|
|
||||||
|
ACCEPTED_CONTENT_TYPES: dict[str, set[str]] = {
|
||||||
|
"image/jpeg": {"image/jpeg", "image/jpg", "image/pjpeg", "application/octet-stream", ""},
|
||||||
|
"image/png": {"image/png", "application/octet-stream", ""},
|
||||||
|
"application/pdf": {"application/pdf", "application/octet-stream", ""},
|
||||||
|
}
|
||||||
|
|
||||||
|
COORDINATOR_UPLOAD_ENTITIES: set[str] = {
|
||||||
|
"contract",
|
||||||
|
"calibration_record",
|
||||||
|
"insurance",
|
||||||
|
"warranty",
|
||||||
|
"demo_equipment",
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
def resolve_entity_department_id(db: Session, entity_type: str, entity_id: int) -> int:
|
||||||
|
if entity_type not in ALLOWED_ENTITY_TYPES:
|
||||||
|
raise CodedHTTPException(
|
||||||
|
status_code=400,
|
||||||
|
detail=f"Unsupported entity_type '{entity_type}'.",
|
||||||
|
code="INVALID_ENTITY_TYPE",
|
||||||
|
)
|
||||||
|
|
||||||
|
if entity_type == "asset":
|
||||||
|
obj = db.query(Asset).filter(Asset.id == entity_id).first()
|
||||||
|
if obj is None:
|
||||||
|
raise CodedHTTPException(status_code=404, detail="Asset not found.", code="NOT_FOUND")
|
||||||
|
return obj.department_id
|
||||||
|
|
||||||
|
if entity_type == "complaint":
|
||||||
|
obj = (
|
||||||
|
db.query(Complaint)
|
||||||
|
.options(joinedload(Complaint.asset))
|
||||||
|
.filter(Complaint.id == entity_id)
|
||||||
|
.first()
|
||||||
|
)
|
||||||
|
if obj is None:
|
||||||
|
raise CodedHTTPException(status_code=404, detail="Complaint not found.", code="NOT_FOUND")
|
||||||
|
return obj.asset.department_id
|
||||||
|
|
||||||
|
if entity_type == "demo_equipment":
|
||||||
|
obj = db.query(DemoEquipment).filter(DemoEquipment.id == entity_id).first()
|
||||||
|
if obj is None:
|
||||||
|
raise CodedHTTPException(status_code=404, detail="Demo equipment not found.", code="NOT_FOUND")
|
||||||
|
return obj.department_id
|
||||||
|
|
||||||
|
if entity_type == "contract":
|
||||||
|
obj = (
|
||||||
|
db.query(Contract)
|
||||||
|
.options(joinedload(Contract.asset))
|
||||||
|
.filter(Contract.id == entity_id)
|
||||||
|
.first()
|
||||||
|
)
|
||||||
|
if obj is None:
|
||||||
|
raise CodedHTTPException(status_code=404, detail="Contract not found.", code="NOT_FOUND")
|
||||||
|
return obj.asset.department_id
|
||||||
|
|
||||||
|
if entity_type == "warranty":
|
||||||
|
obj = (
|
||||||
|
db.query(Warranty)
|
||||||
|
.options(joinedload(Warranty.asset))
|
||||||
|
.filter(Warranty.id == entity_id)
|
||||||
|
.first()
|
||||||
|
)
|
||||||
|
if obj is None:
|
||||||
|
raise CodedHTTPException(status_code=404, detail="Warranty not found.", code="NOT_FOUND")
|
||||||
|
return obj.asset.department_id
|
||||||
|
|
||||||
|
if entity_type == "insurance":
|
||||||
|
obj = (
|
||||||
|
db.query(InsurancePolicy)
|
||||||
|
.options(joinedload(InsurancePolicy.asset))
|
||||||
|
.filter(InsurancePolicy.id == entity_id)
|
||||||
|
.first()
|
||||||
|
)
|
||||||
|
if obj is None:
|
||||||
|
raise CodedHTTPException(status_code=404, detail="Insurance policy not found.", code="NOT_FOUND")
|
||||||
|
return obj.asset.department_id
|
||||||
|
|
||||||
|
if entity_type == "calibration_record":
|
||||||
|
obj = (
|
||||||
|
db.query(CalibrationRecord)
|
||||||
|
.options(joinedload(CalibrationRecord.asset))
|
||||||
|
.filter(CalibrationRecord.id == entity_id)
|
||||||
|
.first()
|
||||||
|
)
|
||||||
|
if obj is None:
|
||||||
|
raise CodedHTTPException(status_code=404, detail="Calibration record not found.", code="NOT_FOUND")
|
||||||
|
return obj.asset.department_id
|
||||||
|
|
||||||
|
raise CodedHTTPException(status_code=400, detail="Unsupported entity_type.", code="INVALID_ENTITY_TYPE")
|
||||||
|
|
||||||
|
|
||||||
|
def assert_entity_visible(db: Session, user: User, entity_type: str, entity_id: int) -> int:
|
||||||
|
dept_id = resolve_entity_department_id(db, entity_type, entity_id)
|
||||||
|
if user.role == Role.department_user.value and dept_id != user.department_id:
|
||||||
|
raise CodedHTTPException(
|
||||||
|
status_code=403,
|
||||||
|
detail="Access denied for another department's record.",
|
||||||
|
code="FORBIDDEN",
|
||||||
|
)
|
||||||
|
return dept_id
|
||||||
|
|
||||||
|
|
||||||
|
def assert_can_upload(user: User, entity_type: str) -> None:
|
||||||
|
if user.role in (Role.system_admin.value, Role.biomedical.value):
|
||||||
|
return
|
||||||
|
if user.role == Role.department_user.value:
|
||||||
|
if entity_type != "complaint":
|
||||||
|
raise CodedHTTPException(
|
||||||
|
status_code=403,
|
||||||
|
detail="Department users may only upload attachments to complaints.",
|
||||||
|
code="FORBIDDEN",
|
||||||
|
)
|
||||||
|
return
|
||||||
|
if user.role == Role.coordinator.value:
|
||||||
|
if entity_type not in COORDINATOR_UPLOAD_ENTITIES:
|
||||||
|
raise CodedHTTPException(
|
||||||
|
status_code=403,
|
||||||
|
detail=f"Coordinators cannot upload attachments to '{entity_type}'.",
|
||||||
|
code="FORBIDDEN",
|
||||||
|
)
|
||||||
|
return
|
||||||
|
raise CodedHTTPException(
|
||||||
|
status_code=403,
|
||||||
|
detail="You do not have permission to upload attachments.",
|
||||||
|
code="FORBIDDEN",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def assert_can_delete(user: User, att: Attachment) -> None:
|
||||||
|
if user.role in (Role.system_admin.value, Role.biomedical.value):
|
||||||
|
return
|
||||||
|
if user.role != Role.management.value and att.uploaded_by_id == user.id:
|
||||||
|
return
|
||||||
|
raise CodedHTTPException(
|
||||||
|
status_code=403,
|
||||||
|
detail="You do not have permission to delete this attachment.",
|
||||||
|
code="FORBIDDEN",
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
def validate_and_read_upload(file: UploadFile) -> tuple[str, str, bytes]:
|
||||||
|
original_name = Path(file.filename or "").name
|
||||||
|
ext = Path(original_name).suffix.lower()
|
||||||
|
if ext not in EXT_TO_MIME:
|
||||||
|
raise CodedHTTPException(
|
||||||
|
status_code=400,
|
||||||
|
detail="Only JPG, JPEG, PNG, and PDF files are allowed.",
|
||||||
|
code="INVALID_FILE_TYPE",
|
||||||
|
)
|
||||||
|
|
||||||
|
expected_mime = EXT_TO_MIME[ext]
|
||||||
|
claimed_type = (file.content_type or "").lower().strip()
|
||||||
|
if claimed_type not in ACCEPTED_CONTENT_TYPES[expected_mime]:
|
||||||
|
raise CodedHTTPException(
|
||||||
|
status_code=400,
|
||||||
|
detail=f"Invalid content type '{claimed_type}' for {ext} file.",
|
||||||
|
code="INVALID_FILE_TYPE",
|
||||||
|
)
|
||||||
|
|
||||||
|
max_bytes = settings.MAX_UPLOAD_SIZE_MB * 1024 * 1024
|
||||||
|
content = file.file.read(max_bytes + 1)
|
||||||
|
if len(content) > max_bytes:
|
||||||
|
raise CodedHTTPException(
|
||||||
|
status_code=413,
|
||||||
|
detail=f"File size exceeds the {settings.MAX_UPLOAD_SIZE_MB} MB limit.",
|
||||||
|
code="FILE_TOO_LARGE",
|
||||||
|
)
|
||||||
|
if len(content) == 0:
|
||||||
|
raise CodedHTTPException(
|
||||||
|
status_code=400,
|
||||||
|
detail="Uploaded file is empty.",
|
||||||
|
code="INVALID_FILE_TYPE",
|
||||||
|
)
|
||||||
|
|
||||||
|
# Magic bytes verification
|
||||||
|
if expected_mime == "image/jpeg" and not content.startswith(b"\xff\xd8\xff"):
|
||||||
|
raise CodedHTTPException(
|
||||||
|
status_code=400,
|
||||||
|
detail="File contents do not match a valid JPEG image.",
|
||||||
|
code="INVALID_FILE_TYPE",
|
||||||
|
)
|
||||||
|
if expected_mime == "image/png" and not content.startswith(b"\x89PNG\r\n\x1a\n"):
|
||||||
|
raise CodedHTTPException(
|
||||||
|
status_code=400,
|
||||||
|
detail="File contents do not match a valid PNG image.",
|
||||||
|
code="INVALID_FILE_TYPE",
|
||||||
|
)
|
||||||
|
if expected_mime == "application/pdf" and not content.startswith(b"%PDF-"):
|
||||||
|
raise CodedHTTPException(
|
||||||
|
status_code=400,
|
||||||
|
detail="File contents do not match a valid PDF document.",
|
||||||
|
code="INVALID_FILE_TYPE",
|
||||||
|
)
|
||||||
|
|
||||||
|
return original_name, expected_mime, content
|
||||||
|
|
||||||
|
|
||||||
|
def save_attachment(
|
||||||
|
db: Session,
|
||||||
|
user: User,
|
||||||
|
entity_type: str,
|
||||||
|
entity_id: int,
|
||||||
|
file: UploadFile,
|
||||||
|
) -> Attachment:
|
||||||
|
assert_entity_visible(db, user, entity_type, entity_id)
|
||||||
|
assert_can_upload(user, entity_type)
|
||||||
|
|
||||||
|
original_name, mime_type, content = validate_and_read_upload(file)
|
||||||
|
ext = Path(original_name).suffix.lower()
|
||||||
|
stored_name = f"{uuid4().hex}{ext}"
|
||||||
|
|
||||||
|
upload_dir = Path(settings.UPLOAD_DIR)
|
||||||
|
upload_dir.mkdir(parents=True, exist_ok=True)
|
||||||
|
dest_path = upload_dir / stored_name
|
||||||
|
dest_path.write_bytes(content)
|
||||||
|
|
||||||
|
att = Attachment(
|
||||||
|
entity_type=entity_type,
|
||||||
|
entity_id=entity_id,
|
||||||
|
original_name=original_name,
|
||||||
|
stored_name=stored_name,
|
||||||
|
mime_type=mime_type,
|
||||||
|
size_bytes=len(content),
|
||||||
|
uploaded_by_id=user.id,
|
||||||
|
uploaded_at=utc_now(),
|
||||||
|
)
|
||||||
|
db.add(att)
|
||||||
|
db.flush()
|
||||||
|
log_audit(
|
||||||
|
db,
|
||||||
|
entity_type="attachment",
|
||||||
|
entity_id=att.id,
|
||||||
|
action="upload",
|
||||||
|
changes={"parent_type": entity_type, "parent_id": entity_id, "original_name": original_name},
|
||||||
|
user_id=user.id,
|
||||||
|
)
|
||||||
|
db.commit()
|
||||||
|
db.refresh(att)
|
||||||
|
return att
|
||||||
|
|
||||||
|
|
||||||
|
def delete_attachment(db: Session, user: User, attachment_id: int) -> None:
|
||||||
|
att = db.query(Attachment).filter(Attachment.id == attachment_id).first()
|
||||||
|
if att is None:
|
||||||
|
raise CodedHTTPException(status_code=404, detail="Attachment not found.", code="NOT_FOUND")
|
||||||
|
|
||||||
|
assert_entity_visible(db, user, att.entity_type, att.entity_id)
|
||||||
|
assert_can_delete(user, att)
|
||||||
|
|
||||||
|
file_path = Path(settings.UPLOAD_DIR) / att.stored_name
|
||||||
|
if file_path.is_file():
|
||||||
|
file_path.unlink()
|
||||||
|
|
||||||
|
log_audit(
|
||||||
|
db,
|
||||||
|
entity_type="attachment",
|
||||||
|
entity_id=att.id,
|
||||||
|
action="delete",
|
||||||
|
changes={"parent_type": att.entity_type, "parent_id": att.entity_id, "original_name": att.original_name},
|
||||||
|
user_id=user.id,
|
||||||
|
)
|
||||||
|
db.delete(att)
|
||||||
|
db.commit()
|
||||||
@@ -0,0 +1,25 @@
|
|||||||
|
import json
|
||||||
|
from typing import Any
|
||||||
|
from sqlalchemy.orm import Session
|
||||||
|
from ..core.time_utils import utc_now
|
||||||
|
from ..models.system import AuditLog
|
||||||
|
|
||||||
|
|
||||||
|
def log_audit(
|
||||||
|
db: Session,
|
||||||
|
entity_type: str,
|
||||||
|
entity_id: int,
|
||||||
|
action: str,
|
||||||
|
changes: dict[str, Any],
|
||||||
|
user_id: int | None,
|
||||||
|
) -> AuditLog:
|
||||||
|
entry = AuditLog(
|
||||||
|
entity_type=entity_type,
|
||||||
|
entity_id=entity_id,
|
||||||
|
action=action,
|
||||||
|
changes_json=json.dumps(changes, default=str),
|
||||||
|
by_user_id=user_id,
|
||||||
|
at=utc_now(),
|
||||||
|
)
|
||||||
|
db.add(entry)
|
||||||
|
return entry
|
||||||
@@ -0,0 +1,62 @@
|
|||||||
|
from datetime import date
|
||||||
|
from typing import Literal
|
||||||
|
|
||||||
|
|
||||||
|
def alert_state(
|
||||||
|
due_date: date | None,
|
||||||
|
today: date,
|
||||||
|
lead_days: int,
|
||||||
|
red_days: int,
|
||||||
|
) -> Literal["ok", "yellow", "red"]:
|
||||||
|
"""Classify a due date into ok/yellow/red alert severity relative to today."""
|
||||||
|
if due_date is None:
|
||||||
|
return "ok"
|
||||||
|
days_left = (due_date - today).days
|
||||||
|
if days_left <= red_days:
|
||||||
|
return "red"
|
||||||
|
if days_left <= lead_days:
|
||||||
|
return "yellow"
|
||||||
|
return "ok"
|
||||||
|
|
||||||
|
|
||||||
|
def coverage_status(
|
||||||
|
start_date: date | None,
|
||||||
|
end_date: date | None,
|
||||||
|
today: date,
|
||||||
|
lead_days: int,
|
||||||
|
red_days: int,
|
||||||
|
) -> tuple[str, str]:
|
||||||
|
"""Compute (status, severity) for a warranty, contract, or insurance policy."""
|
||||||
|
if end_date is None:
|
||||||
|
return ("none", "none")
|
||||||
|
if end_date < today:
|
||||||
|
return ("expired", "red")
|
||||||
|
state = alert_state(end_date, today, lead_days, red_days)
|
||||||
|
if state in ("yellow", "red"):
|
||||||
|
return ("expiring", state)
|
||||||
|
return ("active", "ok")
|
||||||
|
|
||||||
|
|
||||||
|
def compute_schedule_status(
|
||||||
|
due_date: date | None,
|
||||||
|
persisted_status: str | None,
|
||||||
|
today: date,
|
||||||
|
due_window_days: int,
|
||||||
|
red_days: int,
|
||||||
|
) -> tuple[str, str]:
|
||||||
|
"""Compute (status, severity) for calibration or PM records.
|
||||||
|
|
||||||
|
Only 'completed' or 'rescheduled' are stored in DB; upcoming/due/overdue are
|
||||||
|
always derived dynamically against effective_today().
|
||||||
|
"""
|
||||||
|
if persisted_status in ("completed", "rescheduled"):
|
||||||
|
return (persisted_status, "ok")
|
||||||
|
if due_date is None:
|
||||||
|
return ("none", "none")
|
||||||
|
days_left = (due_date - today).days
|
||||||
|
if days_left < 0:
|
||||||
|
return ("overdue", "red")
|
||||||
|
if days_left <= due_window_days:
|
||||||
|
sev = "red" if days_left <= red_days else "yellow"
|
||||||
|
return ("due", sev)
|
||||||
|
return ("upcoming", "ok")
|
||||||
@@ -0,0 +1,336 @@
|
|||||||
|
from datetime import date, timedelta
|
||||||
|
import io
|
||||||
|
from pathlib import Path
|
||||||
|
from PIL import Image
|
||||||
|
import pytest
|
||||||
|
|
||||||
|
from app.core.config import settings
|
||||||
|
from app.models import Asset, AuditLog, Category, Complaint, Department, Location
|
||||||
|
from app.seed.seed import _make_minimal_pdf, seed_database
|
||||||
|
from app.services.calculations import alert_state, compute_schedule_status, coverage_status
|
||||||
|
|
||||||
|
|
||||||
|
@pytest.fixture(scope="module", autouse=True)
|
||||||
|
def seeded_assets_db(db, tmp_path_factory):
|
||||||
|
upload_dir = tmp_path_factory.mktemp("asset_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 _make_png_bytes() -> bytes:
|
||||||
|
buf = io.BytesIO()
|
||||||
|
Image.new("RGB", (32, 32), color=(10, 120, 200)).save(buf, format="PNG")
|
||||||
|
return buf.getvalue()
|
||||||
|
|
||||||
|
|
||||||
|
def _make_jpeg_bytes() -> bytes:
|
||||||
|
buf = io.BytesIO()
|
||||||
|
Image.new("RGB", (32, 32), color=(200, 50, 50)).save(buf, format="JPEG")
|
||||||
|
return buf.getvalue()
|
||||||
|
|
||||||
|
|
||||||
|
def test_alert_state_and_coverage_status():
|
||||||
|
today = date(2026, 5, 1)
|
||||||
|
|
||||||
|
assert alert_state(None, today, lead_days=30, red_days=7) == "ok"
|
||||||
|
assert alert_state(today - timedelta(days=1), today, 30, 7) == "red"
|
||||||
|
assert alert_state(today, today, 30, 7) == "red"
|
||||||
|
assert alert_state(today + timedelta(days=7), today, 30, 7) == "red"
|
||||||
|
assert alert_state(today + timedelta(days=8), today, 30, 7) == "yellow"
|
||||||
|
assert alert_state(today + timedelta(days=30), today, 30, 7) == "yellow"
|
||||||
|
assert alert_state(today + timedelta(days=31), today, 30, 7) == "ok"
|
||||||
|
|
||||||
|
assert coverage_status(None, None, today, 30, 7) == ("none", "none")
|
||||||
|
assert coverage_status(today - timedelta(days=100), today - timedelta(days=1), today, 30, 7) == ("expired", "red")
|
||||||
|
assert coverage_status(today - timedelta(days=100), today + timedelta(days=5), today, 30, 7) == ("expiring", "red")
|
||||||
|
assert coverage_status(today - timedelta(days=100), today + timedelta(days=20), today, 30, 7) == ("expiring", "yellow")
|
||||||
|
assert coverage_status(today - timedelta(days=100), today + timedelta(days=45), today, 30, 7) == ("active", "ok")
|
||||||
|
|
||||||
|
assert compute_schedule_status(today - timedelta(days=1), "completed", today, 15, 7) == ("completed", "ok")
|
||||||
|
assert compute_schedule_status(today - timedelta(days=1), None, today, 15, 7) == ("overdue", "red")
|
||||||
|
assert compute_schedule_status(today + timedelta(days=10), None, today, 15, 7) == ("due", "yellow")
|
||||||
|
assert compute_schedule_status(today + timedelta(days=30), None, today, 15, 7) == ("upcoming", "ok")
|
||||||
|
|
||||||
|
|
||||||
|
def test_asset_crud_and_duplicate_code(client, db):
|
||||||
|
bio_headers = _auth_headers(client, "bio@poona.demo")
|
||||||
|
dept_headers = _auth_headers(client, "dept@poona.demo")
|
||||||
|
icu = db.query(Department).filter(Department.code == "ICU").first()
|
||||||
|
loc = db.query(Location).filter(Location.department_id == icu.id).first()
|
||||||
|
cat = db.query(Category).first()
|
||||||
|
|
||||||
|
# department_user cannot create assets
|
||||||
|
forbidden_create = client.post(
|
||||||
|
"/api/assets",
|
||||||
|
headers=dept_headers,
|
||||||
|
json={
|
||||||
|
"asset_code": "PHRC-ICU-9998",
|
||||||
|
"serial_no": "SN-9998",
|
||||||
|
"name": "Unauthorized Asset",
|
||||||
|
"category_id": cat.id,
|
||||||
|
"department_id": icu.id,
|
||||||
|
"location_id": loc.id,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
assert forbidden_create.status_code == 403
|
||||||
|
|
||||||
|
# biomedical creates asset
|
||||||
|
create_res = client.post(
|
||||||
|
"/api/assets",
|
||||||
|
headers=bio_headers,
|
||||||
|
json={
|
||||||
|
"asset_code": "PHRC-ICU-9999",
|
||||||
|
"serial_no": "SN-TEST-9999",
|
||||||
|
"name": "Test Cardiac Monitor",
|
||||||
|
"category_id": cat.id,
|
||||||
|
"department_id": icu.id,
|
||||||
|
"location_id": loc.id,
|
||||||
|
"purchase_value": 250000.0,
|
||||||
|
"status": "in_service",
|
||||||
|
"criticality": "critical",
|
||||||
|
"requires_calibration": True,
|
||||||
|
"insurance_applicable": True,
|
||||||
|
"remarks": "Phase 2 test asset",
|
||||||
|
},
|
||||||
|
)
|
||||||
|
assert create_res.status_code == 201, create_res.text
|
||||||
|
created = create_res.json()
|
||||||
|
assert created["asset_code"] == "PHRC-ICU-9999"
|
||||||
|
assert created["department_name"] == icu.name
|
||||||
|
|
||||||
|
# Duplicate asset_code -> 409 DUPLICATE_ASSET_CODE
|
||||||
|
dup_res = client.post(
|
||||||
|
"/api/assets",
|
||||||
|
headers=bio_headers,
|
||||||
|
json={
|
||||||
|
"asset_code": "PHRC-ICU-9999",
|
||||||
|
"serial_no": "SN-DUP",
|
||||||
|
"name": "Duplicate Asset",
|
||||||
|
"category_id": cat.id,
|
||||||
|
"department_id": icu.id,
|
||||||
|
"location_id": loc.id,
|
||||||
|
},
|
||||||
|
)
|
||||||
|
assert dup_res.status_code == 409
|
||||||
|
assert dup_res.json()["code"] == "DUPLICATE_ASSET_CODE"
|
||||||
|
|
||||||
|
# Audit log written on create
|
||||||
|
audit = (
|
||||||
|
db.query(AuditLog)
|
||||||
|
.filter(AuditLog.entity_type == "asset", AuditLog.entity_id == created["id"], AuditLog.action == "create")
|
||||||
|
.first()
|
||||||
|
)
|
||||||
|
assert audit is not None
|
||||||
|
|
||||||
|
# Overview returns structured data
|
||||||
|
ov_res = client.get(f"/api/assets/{created['id']}/overview", headers=bio_headers)
|
||||||
|
assert ov_res.status_code == 200
|
||||||
|
ov = ov_res.json()
|
||||||
|
assert ov["asset"]["id"] == created["id"]
|
||||||
|
assert "warranties" in ov
|
||||||
|
assert "contracts" in ov
|
||||||
|
assert "attachments" in ov
|
||||||
|
|
||||||
|
|
||||||
|
def test_department_user_scoping_on_assets(client, db):
|
||||||
|
dept_headers = _auth_headers(client, "dept@poona.demo")
|
||||||
|
icu = db.query(Department).filter(Department.code == "ICU").first()
|
||||||
|
ot = db.query(Department).filter(Department.code == "OT").first()
|
||||||
|
other_asset = db.query(Asset).filter(Asset.department_id == ot.id).first()
|
||||||
|
assert other_asset is not None
|
||||||
|
|
||||||
|
# List returns only ICU assets even if another department_id is requested
|
||||||
|
list_res = client.get(f"/api/assets?department_id={ot.id}&page_size=200", headers=dept_headers)
|
||||||
|
assert list_res.status_code == 200
|
||||||
|
items = list_res.json()["items"]
|
||||||
|
assert len(items) > 0
|
||||||
|
assert all(item["department_id"] == icu.id for item in items)
|
||||||
|
|
||||||
|
# Lookup returns only ICU assets
|
||||||
|
lookup_res = client.get(f"/api/assets/lookup?department_id={ot.id}", headers=dept_headers)
|
||||||
|
assert lookup_res.status_code == 200
|
||||||
|
lookup_items = lookup_res.json()["items"]
|
||||||
|
assert all(item["department_id"] == icu.id for item in lookup_items)
|
||||||
|
|
||||||
|
# Direct access to another department's asset & overview -> 403
|
||||||
|
assert client.get(f"/api/assets/{other_asset.id}", headers=dept_headers).status_code == 403
|
||||||
|
assert client.get(f"/api/assets/{other_asset.id}/overview", headers=dept_headers).status_code == 403
|
||||||
|
|
||||||
|
|
||||||
|
def test_coordinator_field_level_patch_restrictions(client, db):
|
||||||
|
coord_headers = _auth_headers(client, "coord@poona.demo")
|
||||||
|
asset = db.query(Asset).first()
|
||||||
|
|
||||||
|
ok_patch = client.patch(
|
||||||
|
f"/api/assets/{asset.id}",
|
||||||
|
headers=coord_headers,
|
||||||
|
json={"insurance_applicable": not asset.insurance_applicable, "remarks": "Updated by coordinator"},
|
||||||
|
)
|
||||||
|
assert ok_patch.status_code == 200
|
||||||
|
assert ok_patch.json()["remarks"] == "Updated by coordinator"
|
||||||
|
|
||||||
|
bad_name = client.patch(
|
||||||
|
f"/api/assets/{asset.id}",
|
||||||
|
headers=coord_headers,
|
||||||
|
json={"name": "Unauthorized Rename"},
|
||||||
|
)
|
||||||
|
assert bad_name.status_code == 403
|
||||||
|
assert bad_name.json()["code"] == "FORBIDDEN"
|
||||||
|
|
||||||
|
bad_status = client.patch(
|
||||||
|
f"/api/assets/{asset.id}",
|
||||||
|
headers=coord_headers,
|
||||||
|
json={"status": "condemned"},
|
||||||
|
)
|
||||||
|
assert bad_status.status_code == 403
|
||||||
|
assert bad_status.json()["code"] == "FORBIDDEN"
|
||||||
|
|
||||||
|
|
||||||
|
def test_attachments_upload_download_delete_and_security(client, db, tmp_path, monkeypatch):
|
||||||
|
monkeypatch.setattr(settings, "UPLOAD_DIR", str(tmp_path))
|
||||||
|
|
||||||
|
bio_headers = _auth_headers(client, "bio@poona.demo")
|
||||||
|
dept_headers = _auth_headers(client, "dept@poona.demo")
|
||||||
|
mgmt_headers = _auth_headers(client, "mgmt@poona.demo")
|
||||||
|
|
||||||
|
icu = db.query(Department).filter(Department.code == "ICU").first()
|
||||||
|
ot = db.query(Department).filter(Department.code == "OT").first()
|
||||||
|
icu_asset = db.query(Asset).filter(Asset.department_id == icu.id).first()
|
||||||
|
ot_asset = db.query(Asset).filter(Asset.department_id == ot.id).first()
|
||||||
|
icu_complaint = (
|
||||||
|
db.query(Complaint)
|
||||||
|
.join(Asset, Complaint.asset_id == Asset.id)
|
||||||
|
.filter(Asset.department_id == icu.id)
|
||||||
|
.first()
|
||||||
|
)
|
||||||
|
assert icu_complaint is not None
|
||||||
|
|
||||||
|
# 1. Valid PNG upload & download exact bytes
|
||||||
|
png_bytes = _make_png_bytes()
|
||||||
|
up_png = client.post(
|
||||||
|
"/api/attachments",
|
||||||
|
headers=bio_headers,
|
||||||
|
data={"entity_type": "asset", "entity_id": str(icu_asset.id)},
|
||||||
|
files={"file": ("panel.png", png_bytes, "image/png")},
|
||||||
|
)
|
||||||
|
assert up_png.status_code == 201, up_png.text
|
||||||
|
att_id = up_png.json()["id"]
|
||||||
|
assert up_png.json()["mime_type"] == "image/png"
|
||||||
|
|
||||||
|
dl_res = client.get(f"/api/attachments/{att_id}/download", headers=bio_headers)
|
||||||
|
assert dl_res.status_code == 200
|
||||||
|
assert dl_res.content == png_bytes
|
||||||
|
|
||||||
|
# 2. Valid JPG and PDF uploads
|
||||||
|
jpg_bytes = _make_jpeg_bytes()
|
||||||
|
up_jpg = client.post(
|
||||||
|
"/api/attachments",
|
||||||
|
headers=bio_headers,
|
||||||
|
data={"entity_type": "asset", "entity_id": str(icu_asset.id)},
|
||||||
|
files={"file": ("photo.jpg", jpg_bytes, "image/jpeg")},
|
||||||
|
)
|
||||||
|
assert up_jpg.status_code == 201
|
||||||
|
|
||||||
|
pdf_bytes = _make_minimal_pdf("Asset Service Manual")
|
||||||
|
up_pdf = client.post(
|
||||||
|
"/api/attachments",
|
||||||
|
headers=bio_headers,
|
||||||
|
data={"entity_type": "asset", "entity_id": str(icu_asset.id)},
|
||||||
|
files={"file": ("manual.pdf", pdf_bytes, "application/pdf")},
|
||||||
|
)
|
||||||
|
assert up_pdf.status_code == 201
|
||||||
|
|
||||||
|
# 3. Reject .exe / .txt and spoofed magic bytes -> 400 INVALID_FILE_TYPE
|
||||||
|
bad_exe = client.post(
|
||||||
|
"/api/attachments",
|
||||||
|
headers=bio_headers,
|
||||||
|
data={"entity_type": "asset", "entity_id": str(icu_asset.id)},
|
||||||
|
files={"file": ("malware.exe", b"MZ\x90\x00", "application/octet-stream")},
|
||||||
|
)
|
||||||
|
assert bad_exe.status_code == 400
|
||||||
|
assert bad_exe.json()["code"] == "INVALID_FILE_TYPE"
|
||||||
|
|
||||||
|
bad_spoof = client.post(
|
||||||
|
"/api/attachments",
|
||||||
|
headers=bio_headers,
|
||||||
|
data={"entity_type": "asset", "entity_id": str(icu_asset.id)},
|
||||||
|
files={"file": ("fake.jpg", b"not really a jpeg", "image/jpeg")},
|
||||||
|
)
|
||||||
|
assert bad_spoof.status_code == 400
|
||||||
|
assert bad_spoof.json()["code"] == "INVALID_FILE_TYPE"
|
||||||
|
|
||||||
|
# 4. Reject >10 MB -> 413 FILE_TOO_LARGE
|
||||||
|
oversized = b"%PDF-" + (b"0" * (10 * 1024 * 1024 + 100))
|
||||||
|
too_big = client.post(
|
||||||
|
"/api/attachments",
|
||||||
|
headers=bio_headers,
|
||||||
|
data={"entity_type": "asset", "entity_id": str(icu_asset.id)},
|
||||||
|
files={"file": ("huge.pdf", oversized, "application/pdf")},
|
||||||
|
)
|
||||||
|
assert too_big.status_code == 413
|
||||||
|
assert too_big.json()["code"] == "FILE_TOO_LARGE"
|
||||||
|
|
||||||
|
# 5. department_user cannot upload to or download from another department's asset
|
||||||
|
ot_up = client.post(
|
||||||
|
"/api/attachments",
|
||||||
|
headers=bio_headers,
|
||||||
|
data={"entity_type": "asset", "entity_id": str(ot_asset.id)},
|
||||||
|
files={"file": ("ot.png", png_bytes, "image/png")},
|
||||||
|
)
|
||||||
|
assert ot_up.status_code == 201
|
||||||
|
ot_att_id = ot_up.json()["id"]
|
||||||
|
|
||||||
|
assert client.get(f"/api/attachments/{ot_att_id}/download", headers=dept_headers).status_code == 403
|
||||||
|
assert (
|
||||||
|
client.post(
|
||||||
|
"/api/attachments",
|
||||||
|
headers=dept_headers,
|
||||||
|
data={"entity_type": "asset", "entity_id": str(ot_asset.id)},
|
||||||
|
files={"file": ("unauth.png", png_bytes, "image/png")},
|
||||||
|
).status_code
|
||||||
|
== 403
|
||||||
|
)
|
||||||
|
|
||||||
|
# department_user cannot upload to own-dept asset (only complaint), CAN upload to own-dept complaint
|
||||||
|
assert (
|
||||||
|
client.post(
|
||||||
|
"/api/attachments",
|
||||||
|
headers=dept_headers,
|
||||||
|
data={"entity_type": "asset", "entity_id": str(icu_asset.id)},
|
||||||
|
files={"file": ("icu.png", png_bytes, "image/png")},
|
||||||
|
).status_code
|
||||||
|
== 403
|
||||||
|
)
|
||||||
|
dept_cmp_up = client.post(
|
||||||
|
"/api/attachments",
|
||||||
|
headers=dept_headers,
|
||||||
|
data={"entity_type": "complaint", "entity_id": str(icu_complaint.id)},
|
||||||
|
files={"file": ("fault.jpg", jpg_bytes, "image/jpeg")},
|
||||||
|
)
|
||||||
|
assert dept_cmp_up.status_code == 201
|
||||||
|
|
||||||
|
# management cannot upload or delete
|
||||||
|
assert (
|
||||||
|
client.post(
|
||||||
|
"/api/attachments",
|
||||||
|
headers=mgmt_headers,
|
||||||
|
data={"entity_type": "asset", "entity_id": str(icu_asset.id)},
|
||||||
|
files={"file": ("mgmt.png", png_bytes, "image/png")},
|
||||||
|
).status_code
|
||||||
|
== 403
|
||||||
|
)
|
||||||
|
assert client.delete(f"/api/attachments/{att_id}", headers=mgmt_headers).status_code == 403
|
||||||
|
|
||||||
|
# Delete removes DB row and disk file
|
||||||
|
stored_files_before = list(Path(tmp_path).iterdir())
|
||||||
|
del_res = client.delete(f"/api/attachments/{att_id}", headers=bio_headers)
|
||||||
|
assert del_res.status_code == 204
|
||||||
|
stored_files_after = list(Path(tmp_path).iterdir())
|
||||||
|
assert len(stored_files_after) == len(stored_files_before) - 1
|
||||||
|
assert client.get(f"/api/attachments/{att_id}/download", headers=bio_headers).status_code == 404
|
||||||
@@ -7,9 +7,10 @@ import { LoginPage } from "@/pages/LoginPage";
|
|||||||
import { AccessDeniedPage } from "@/pages/AccessDeniedPage";
|
import { AccessDeniedPage } from "@/pages/AccessDeniedPage";
|
||||||
import { MastersPage } from "@/pages/MastersPage";
|
import { MastersPage } from "@/pages/MastersPage";
|
||||||
import { SettingsPage } from "@/pages/SettingsPage";
|
import { SettingsPage } from "@/pages/SettingsPage";
|
||||||
|
import { AssetsPage } from "@/pages/AssetsPage";
|
||||||
|
import { AssetDetailPage } from "@/pages/AssetDetailPage";
|
||||||
import {
|
import {
|
||||||
DashboardPage,
|
DashboardPage,
|
||||||
AssetsPage,
|
|
||||||
ComplaintsPage,
|
ComplaintsPage,
|
||||||
PMPage,
|
PMPage,
|
||||||
CalibrationPage,
|
CalibrationPage,
|
||||||
@@ -81,6 +82,7 @@ function AppRoutes() {
|
|||||||
>
|
>
|
||||||
<Route path="/" element={<DashboardPage />} />
|
<Route path="/" element={<DashboardPage />} />
|
||||||
<Route path="/assets" element={<AssetsPage />} />
|
<Route path="/assets" element={<AssetsPage />} />
|
||||||
|
<Route path="/assets/:id" element={<AssetDetailPage />} />
|
||||||
<Route path="/complaints" element={<ComplaintsPage />} />
|
<Route path="/complaints" element={<ComplaintsPage />} />
|
||||||
<Route path="/pm" element={<PMPage />} />
|
<Route path="/pm" element={<PMPage />} />
|
||||||
<Route path="/calibration" element={<CalibrationPage />} />
|
<Route path="/calibration" element={<CalibrationPage />} />
|
||||||
|
|||||||
@@ -0,0 +1,254 @@
|
|||||||
|
import { api } from "./client";
|
||||||
|
import type { AttachmentItem } from "./attachments";
|
||||||
|
|
||||||
|
export type AssetStatus = "in_service" | "under_repair" | "out_of_service" | "condemned";
|
||||||
|
export type AssetCriticality = "critical" | "non_critical";
|
||||||
|
export type CoverageStatus = "active" | "expiring" | "expired" | "none";
|
||||||
|
export type AlertSeverity = "ok" | "yellow" | "red" | "none";
|
||||||
|
export type CalibrationStatus = "upcoming" | "due" | "overdue" | "completed" | "none";
|
||||||
|
|
||||||
|
export interface AssetItem {
|
||||||
|
id: number;
|
||||||
|
asset_code: string;
|
||||||
|
serial_no: string;
|
||||||
|
name: string;
|
||||||
|
category_id: number;
|
||||||
|
category_name: string | null;
|
||||||
|
department_id: number;
|
||||||
|
department_name: string | null;
|
||||||
|
location_id: number;
|
||||||
|
location_name: string | null;
|
||||||
|
supplier_id: number | null;
|
||||||
|
supplier_name: string | null;
|
||||||
|
purchase_value: number | null;
|
||||||
|
purchase_date: string | null;
|
||||||
|
installation_date: string | null;
|
||||||
|
status: AssetStatus;
|
||||||
|
criticality: AssetCriticality;
|
||||||
|
requires_calibration: boolean;
|
||||||
|
insurance_applicable: boolean;
|
||||||
|
remarks: string | null;
|
||||||
|
warranty_status: CoverageStatus;
|
||||||
|
warranty_end_date: string | null;
|
||||||
|
warranty_severity: AlertSeverity;
|
||||||
|
contract_status: CoverageStatus;
|
||||||
|
contract_type: string | null;
|
||||||
|
contract_end_date: string | null;
|
||||||
|
contract_severity: AlertSeverity;
|
||||||
|
calibration_status: CalibrationStatus;
|
||||||
|
calibration_due_date: string | null;
|
||||||
|
calibration_severity: AlertSeverity;
|
||||||
|
insurance_status: CoverageStatus;
|
||||||
|
insurance_end_date: string | null;
|
||||||
|
created_at: string;
|
||||||
|
updated_at: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AssetLookupItem {
|
||||||
|
id: number;
|
||||||
|
asset_code: string;
|
||||||
|
serial_no: string;
|
||||||
|
name: string;
|
||||||
|
category_id: number;
|
||||||
|
category_name: string | null;
|
||||||
|
department_id: number;
|
||||||
|
department_name: string | null;
|
||||||
|
location_id: number;
|
||||||
|
location_name: string | null;
|
||||||
|
supplier_id: number | null;
|
||||||
|
supplier_name: string | null;
|
||||||
|
status: AssetStatus;
|
||||||
|
criticality: AssetCriticality;
|
||||||
|
requires_calibration: boolean;
|
||||||
|
insurance_applicable: boolean;
|
||||||
|
warranty_status: CoverageStatus;
|
||||||
|
warranty_end_date: string | null;
|
||||||
|
contract_status: CoverageStatus;
|
||||||
|
contract_type: string | null;
|
||||||
|
contract_end_date: string | null;
|
||||||
|
contract_summary: string;
|
||||||
|
insurance_status: CoverageStatus;
|
||||||
|
insurance_end_date: string | null;
|
||||||
|
insurance_summary: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface WarrantySummary {
|
||||||
|
id: number;
|
||||||
|
asset_id: number;
|
||||||
|
duration_months: number;
|
||||||
|
start_date: string;
|
||||||
|
end_date: string;
|
||||||
|
provider_id: number | null;
|
||||||
|
provider_name: string | null;
|
||||||
|
status: CoverageStatus | string;
|
||||||
|
severity: AlertSeverity | string;
|
||||||
|
remarks: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ContractSummary {
|
||||||
|
id: number;
|
||||||
|
asset_id: number;
|
||||||
|
contract_type: string;
|
||||||
|
provider_id: number;
|
||||||
|
provider_name: string | null;
|
||||||
|
start_date: string;
|
||||||
|
end_date: string;
|
||||||
|
coverage_period_text: string | null;
|
||||||
|
renewed_from_id: number | null;
|
||||||
|
is_superseded: boolean;
|
||||||
|
status: CoverageStatus | string;
|
||||||
|
severity: AlertSeverity | string;
|
||||||
|
remarks: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface InsuranceSummary {
|
||||||
|
id: number;
|
||||||
|
asset_id: number;
|
||||||
|
insurer_id: number;
|
||||||
|
insurer_name: string | null;
|
||||||
|
policy_no: string;
|
||||||
|
start_date: string;
|
||||||
|
end_date: string;
|
||||||
|
coverage_amount: number | null;
|
||||||
|
status: CoverageStatus | string;
|
||||||
|
severity: AlertSeverity | string;
|
||||||
|
remarks: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CalibrationPlanSummary {
|
||||||
|
id: number;
|
||||||
|
asset_id: number;
|
||||||
|
frequency_months: number;
|
||||||
|
calibrations_per_year: number;
|
||||||
|
agency_id: number | null;
|
||||||
|
agency_name: string | null;
|
||||||
|
approved_by_id: number | null;
|
||||||
|
approved_on: string | null;
|
||||||
|
next_due_date: string;
|
||||||
|
is_active: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface CalibrationRecordSummary {
|
||||||
|
id: number;
|
||||||
|
asset_id: number;
|
||||||
|
plan_id: number;
|
||||||
|
due_date: string;
|
||||||
|
completed_date: string | null;
|
||||||
|
agency_id: number | null;
|
||||||
|
agency_name: string | null;
|
||||||
|
certificate_no: string | null;
|
||||||
|
remarks: string | null;
|
||||||
|
status: CalibrationStatus | string;
|
||||||
|
severity: AlertSeverity | string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PMScheduleSummary {
|
||||||
|
id: number;
|
||||||
|
asset_id: number;
|
||||||
|
service_mode: string;
|
||||||
|
frequency_months: number;
|
||||||
|
responsible_team: string | null;
|
||||||
|
provider_id: number | null;
|
||||||
|
provider_name: string | null;
|
||||||
|
contract_id: number | null;
|
||||||
|
next_planned_date: string;
|
||||||
|
is_active: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface PMRecordSummary {
|
||||||
|
id: number;
|
||||||
|
schedule_id: number;
|
||||||
|
asset_id: number;
|
||||||
|
planned_date: string;
|
||||||
|
completed_date: string | null;
|
||||||
|
status: string;
|
||||||
|
severity: string;
|
||||||
|
service_details: string | null;
|
||||||
|
remarks: string | null;
|
||||||
|
rescheduled_to: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface ComplaintSummary {
|
||||||
|
id: number;
|
||||||
|
complaint_no: string;
|
||||||
|
asset_id: number;
|
||||||
|
description: string;
|
||||||
|
priority: string;
|
||||||
|
call_status: string;
|
||||||
|
registered_at: string;
|
||||||
|
closed_at: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AssetOverview {
|
||||||
|
asset: AssetItem;
|
||||||
|
warranties: WarrantySummary[];
|
||||||
|
contracts: ContractSummary[];
|
||||||
|
insurance_policies: InsuranceSummary[];
|
||||||
|
calibration_plan: CalibrationPlanSummary | null;
|
||||||
|
calibration_records: CalibrationRecordSummary[];
|
||||||
|
pm_schedules: PMScheduleSummary[];
|
||||||
|
pm_records: PMRecordSummary[];
|
||||||
|
complaints: ComplaintSummary[];
|
||||||
|
attachments: AttachmentItem[];
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AssetListParams {
|
||||||
|
q?: string;
|
||||||
|
department_id?: number;
|
||||||
|
category_id?: number;
|
||||||
|
location_id?: number;
|
||||||
|
supplier_id?: number;
|
||||||
|
status?: AssetStatus | "";
|
||||||
|
criticality?: AssetCriticality | "";
|
||||||
|
page?: number;
|
||||||
|
page_size?: number;
|
||||||
|
sort?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export interface AssetCreatePayload {
|
||||||
|
asset_code: string;
|
||||||
|
serial_no: string;
|
||||||
|
name: string;
|
||||||
|
category_id: number;
|
||||||
|
department_id: number;
|
||||||
|
location_id: number;
|
||||||
|
supplier_id?: number | null;
|
||||||
|
purchase_value?: number | null;
|
||||||
|
purchase_date?: string | null;
|
||||||
|
installation_date?: string | null;
|
||||||
|
status: AssetStatus;
|
||||||
|
criticality: AssetCriticality;
|
||||||
|
requires_calibration: boolean;
|
||||||
|
insurance_applicable: boolean;
|
||||||
|
remarks?: string | null;
|
||||||
|
}
|
||||||
|
|
||||||
|
export type AssetUpdatePayload = Partial<AssetCreatePayload>;
|
||||||
|
|
||||||
|
export const assetsApi = {
|
||||||
|
list: (params: AssetListParams = {}) => {
|
||||||
|
const qs = new URLSearchParams();
|
||||||
|
if (params.q) qs.set("q", params.q);
|
||||||
|
if (params.department_id) qs.set("department_id", String(params.department_id));
|
||||||
|
if (params.category_id) qs.set("category_id", String(params.category_id));
|
||||||
|
if (params.location_id) qs.set("location_id", String(params.location_id));
|
||||||
|
if (params.supplier_id) qs.set("supplier_id", String(params.supplier_id));
|
||||||
|
if (params.status) qs.set("status", params.status);
|
||||||
|
if (params.criticality) qs.set("criticality", params.criticality);
|
||||||
|
qs.set("page", String(params.page ?? 1));
|
||||||
|
qs.set("page_size", String(params.page_size ?? 200));
|
||||||
|
if (params.sort) qs.set("sort", params.sort);
|
||||||
|
return api.get<{ items: AssetItem[]; total: number }>(`/assets?${qs.toString()}`);
|
||||||
|
},
|
||||||
|
lookup: (params: { q?: string; department_id?: number; limit?: number } = {}) => {
|
||||||
|
const qs = new URLSearchParams();
|
||||||
|
if (params.q !== undefined) qs.set("q", params.q);
|
||||||
|
if (params.department_id) qs.set("department_id", String(params.department_id));
|
||||||
|
qs.set("limit", String(params.limit ?? 25));
|
||||||
|
return api.get<{ items: AssetLookupItem[] }>(`/assets/lookup?${qs.toString()}`);
|
||||||
|
},
|
||||||
|
get: (id: number) => api.get<AssetItem>(`/assets/${id}`),
|
||||||
|
overview: (id: number) => api.get<AssetOverview>(`/assets/${id}/overview`),
|
||||||
|
create: (data: AssetCreatePayload) => api.post<AssetItem>("/assets", data),
|
||||||
|
update: (id: number, data: AssetUpdatePayload) => api.patch<AssetItem>(`/assets/${id}`, data),
|
||||||
|
};
|
||||||
@@ -0,0 +1,56 @@
|
|||||||
|
import { api } from "./client";
|
||||||
|
|
||||||
|
export type AttachmentEntityType =
|
||||||
|
| "complaint"
|
||||||
|
| "contract"
|
||||||
|
| "calibration_record"
|
||||||
|
| "insurance"
|
||||||
|
| "demo_equipment"
|
||||||
|
| "asset"
|
||||||
|
| "warranty";
|
||||||
|
|
||||||
|
export interface AttachmentItem {
|
||||||
|
id: number;
|
||||||
|
entity_type: AttachmentEntityType | string;
|
||||||
|
entity_id: number;
|
||||||
|
original_name: string;
|
||||||
|
mime_type: string;
|
||||||
|
size_bytes: number;
|
||||||
|
uploaded_by_id?: number | null;
|
||||||
|
uploaded_by_name?: string | null;
|
||||||
|
uploaded_at: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export const attachmentsApi = {
|
||||||
|
list: (entityType: AttachmentEntityType, entityId: number) => {
|
||||||
|
const qs = new URLSearchParams({
|
||||||
|
entity_type: entityType,
|
||||||
|
entity_id: String(entityId),
|
||||||
|
});
|
||||||
|
return api.get<{ items: AttachmentItem[]; total: number }>(`/attachments?${qs.toString()}`);
|
||||||
|
},
|
||||||
|
upload: (entityType: AttachmentEntityType, entityId: number, file: File) => {
|
||||||
|
const formData = new FormData();
|
||||||
|
formData.append("entity_type", entityType);
|
||||||
|
formData.append("entity_id", String(entityId));
|
||||||
|
formData.append("file", file);
|
||||||
|
return api.upload<AttachmentItem>("/attachments", formData);
|
||||||
|
},
|
||||||
|
download: async (id: number, originalName: string, preview = false) => {
|
||||||
|
const { blob } = await api.downloadBlob(`/attachments/${id}/download`);
|
||||||
|
const url = URL.createObjectURL(blob);
|
||||||
|
if (preview) {
|
||||||
|
window.open(url, "_blank", "noopener,noreferrer");
|
||||||
|
setTimeout(() => URL.revokeObjectURL(url), 30_000);
|
||||||
|
} else {
|
||||||
|
const a = document.createElement("a");
|
||||||
|
a.href = url;
|
||||||
|
a.download = originalName;
|
||||||
|
document.body.appendChild(a);
|
||||||
|
a.click();
|
||||||
|
a.remove();
|
||||||
|
URL.revokeObjectURL(url);
|
||||||
|
}
|
||||||
|
},
|
||||||
|
remove: (id: number) => api.delete<void>(`/attachments/${id}`),
|
||||||
|
};
|
||||||
@@ -16,10 +16,18 @@ export function setUnauthorizedHandler(cb: () => void) {
|
|||||||
onUnauthorizedCallback = cb;
|
onUnauthorizedCallback = cb;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
function handleUnauthorized(path: string) {
|
||||||
|
sessionStorage.removeItem("access_token");
|
||||||
|
if (!path.startsWith("/auth/login")) {
|
||||||
|
onUnauthorizedCallback?.();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
async function request<T>(path: string, options: RequestInit = {}): Promise<T> {
|
async function request<T>(path: string, options: RequestInit = {}): Promise<T> {
|
||||||
const token = sessionStorage.getItem("access_token");
|
const token = sessionStorage.getItem("access_token");
|
||||||
|
const isFormData = typeof FormData !== "undefined" && options.body instanceof FormData;
|
||||||
const headers: Record<string, string> = {
|
const headers: Record<string, string> = {
|
||||||
"Content-Type": "application/json",
|
...(isFormData ? {} : { "Content-Type": "application/json" }),
|
||||||
...(options.headers as Record<string, string>),
|
...(options.headers as Record<string, string>),
|
||||||
};
|
};
|
||||||
if (token) headers["Authorization"] = `Bearer ${token}`;
|
if (token) headers["Authorization"] = `Bearer ${token}`;
|
||||||
@@ -27,16 +35,29 @@ async function request<T>(path: string, options: RequestInit = {}): Promise<T> {
|
|||||||
const res = await fetch(`${BASE_URL}${path}`, { ...options, headers });
|
const res = await fetch(`${BASE_URL}${path}`, { ...options, headers });
|
||||||
if (!res.ok) {
|
if (!res.ok) {
|
||||||
const body = await res.json().catch(() => ({ detail: res.statusText }));
|
const body = await res.json().catch(() => ({ detail: res.statusText }));
|
||||||
if (res.status === 401 && !path.startsWith("/auth/login")) {
|
if (res.status === 401) handleUnauthorized(path);
|
||||||
sessionStorage.removeItem("access_token");
|
|
||||||
onUnauthorizedCallback?.();
|
|
||||||
}
|
|
||||||
throw new ApiError(res.status, body.detail ?? res.statusText, body.code);
|
throw new ApiError(res.status, body.detail ?? res.statusText, body.code);
|
||||||
}
|
}
|
||||||
if (res.status === 204) return undefined as T;
|
if (res.status === 204) return undefined as T;
|
||||||
return res.json();
|
return res.json();
|
||||||
}
|
}
|
||||||
|
|
||||||
|
async function downloadBlob(path: string): Promise<{ blob: Blob; contentType: string }> {
|
||||||
|
const token = sessionStorage.getItem("access_token");
|
||||||
|
const headers: Record<string, string> = {};
|
||||||
|
if (token) headers["Authorization"] = `Bearer ${token}`;
|
||||||
|
|
||||||
|
const res = await fetch(`${BASE_URL}${path}`, { headers });
|
||||||
|
if (!res.ok) {
|
||||||
|
const body = await res.json().catch(() => ({ detail: res.statusText }));
|
||||||
|
if (res.status === 401) handleUnauthorized(path);
|
||||||
|
throw new ApiError(res.status, body.detail ?? res.statusText, body.code);
|
||||||
|
}
|
||||||
|
const blob = await res.blob();
|
||||||
|
const contentType = res.headers.get("Content-Type") || blob.type || "application/octet-stream";
|
||||||
|
return { blob, contentType };
|
||||||
|
}
|
||||||
|
|
||||||
export const api = {
|
export const api = {
|
||||||
get: <T>(path: string) => request<T>(path),
|
get: <T>(path: string) => request<T>(path),
|
||||||
post: <T>(path: string, data?: unknown) =>
|
post: <T>(path: string, data?: unknown) =>
|
||||||
@@ -46,4 +67,7 @@ export const api = {
|
|||||||
put: <T>(path: string, data: unknown) =>
|
put: <T>(path: string, data: unknown) =>
|
||||||
request<T>(path, { method: "PUT", body: JSON.stringify(data) }),
|
request<T>(path, { method: "PUT", body: JSON.stringify(data) }),
|
||||||
delete: <T>(path: string) => request<T>(path, { method: "DELETE" }),
|
delete: <T>(path: string) => request<T>(path, { method: "DELETE" }),
|
||||||
|
upload: <T>(path: string, formData: FormData) =>
|
||||||
|
request<T>(path, { method: "POST", body: formData }),
|
||||||
|
downloadBlob,
|
||||||
};
|
};
|
||||||
|
|||||||
@@ -0,0 +1,433 @@
|
|||||||
|
import { useState, useEffect, useMemo } from "react";
|
||||||
|
import { useQuery, useQueryClient } from "@tanstack/react-query";
|
||||||
|
import { useForm } from "react-hook-form";
|
||||||
|
import { zodResolver } from "@hookform/resolvers/zod";
|
||||||
|
import { z } from "zod";
|
||||||
|
import { AlertCircle } from "lucide-react";
|
||||||
|
import { Modal } from "@/components/ui/dialog";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { ApiError } from "@/api/client";
|
||||||
|
import {
|
||||||
|
assetsApi,
|
||||||
|
type AssetItem,
|
||||||
|
type AssetStatus,
|
||||||
|
type AssetCriticality,
|
||||||
|
} from "@/api/assets";
|
||||||
|
import {
|
||||||
|
departmentsApi,
|
||||||
|
locationsApi,
|
||||||
|
categoriesApi,
|
||||||
|
vendorsApi,
|
||||||
|
} from "@/api/masters";
|
||||||
|
|
||||||
|
const assetSchema = z.object({
|
||||||
|
asset_code: z.string().trim().min(1, "Asset code is required"),
|
||||||
|
serial_no: z.string().trim().min(1, "Serial number is required"),
|
||||||
|
name: z.string().trim().min(1, "Equipment name is required"),
|
||||||
|
category_id: z.coerce.number().int().min(1, "Select a category"),
|
||||||
|
department_id: z.coerce.number().int().min(1, "Select a department"),
|
||||||
|
location_id: z.coerce.number().int().min(1, "Select a location"),
|
||||||
|
supplier_id: z.string().optional(),
|
||||||
|
purchase_value: z.string().optional(),
|
||||||
|
purchase_date: z.string().optional(),
|
||||||
|
installation_date: z.string().optional(),
|
||||||
|
status: z.enum(["in_service", "under_repair", "out_of_service", "condemned"]),
|
||||||
|
criticality: z.enum(["critical", "non_critical"]),
|
||||||
|
requires_calibration: z.boolean(),
|
||||||
|
insurance_applicable: z.boolean(),
|
||||||
|
remarks: z.string().optional(),
|
||||||
|
});
|
||||||
|
|
||||||
|
type AssetFormValues = z.infer<typeof assetSchema>;
|
||||||
|
|
||||||
|
interface AssetFormModalProps {
|
||||||
|
open: boolean;
|
||||||
|
onClose: () => void;
|
||||||
|
editing?: AssetItem | null;
|
||||||
|
coordinatorOnly?: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
const inputCls =
|
||||||
|
"w-full px-3 py-2 text-sm border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 disabled:bg-gray-100 disabled:text-gray-500";
|
||||||
|
const labelCls = "block text-sm font-medium text-gray-700 mb-1";
|
||||||
|
const errCls = "text-xs text-red-600 mt-1";
|
||||||
|
|
||||||
|
export function AssetFormModal({
|
||||||
|
open,
|
||||||
|
onClose,
|
||||||
|
editing = null,
|
||||||
|
coordinatorOnly = false,
|
||||||
|
}: AssetFormModalProps) {
|
||||||
|
const qc = useQueryClient();
|
||||||
|
const [serverError, setServerError] = useState<string | null>(null);
|
||||||
|
|
||||||
|
const deptsQuery = useQuery({
|
||||||
|
queryKey: ["departments", "active-only"],
|
||||||
|
queryFn: () => departmentsApi.list(false),
|
||||||
|
enabled: open,
|
||||||
|
});
|
||||||
|
const locsQuery = useQuery({
|
||||||
|
queryKey: ["locations", "active-only"],
|
||||||
|
queryFn: () => locationsApi.list(false),
|
||||||
|
enabled: open,
|
||||||
|
});
|
||||||
|
const catsQuery = useQuery({
|
||||||
|
queryKey: ["categories", "active-only"],
|
||||||
|
queryFn: () => categoriesApi.list(false),
|
||||||
|
enabled: open,
|
||||||
|
});
|
||||||
|
const vendorsQuery = useQuery({
|
||||||
|
queryKey: ["vendors", "active-only"],
|
||||||
|
queryFn: () => vendorsApi.list(false),
|
||||||
|
enabled: open,
|
||||||
|
});
|
||||||
|
|
||||||
|
const departments = deptsQuery.data?.items ?? [];
|
||||||
|
const allLocations = locsQuery.data?.items ?? [];
|
||||||
|
const categories = catsQuery.data?.items ?? [];
|
||||||
|
const vendors = vendorsQuery.data?.items ?? [];
|
||||||
|
|
||||||
|
const defaultDeptId = editing?.department_id ?? departments[0]?.id ?? 0;
|
||||||
|
const defaultLocId =
|
||||||
|
editing?.location_id ??
|
||||||
|
allLocations.find((l) => l.department_id === defaultDeptId)?.id ??
|
||||||
|
0;
|
||||||
|
|
||||||
|
const {
|
||||||
|
register,
|
||||||
|
handleSubmit,
|
||||||
|
watch,
|
||||||
|
setValue,
|
||||||
|
reset,
|
||||||
|
formState: { errors, isSubmitting },
|
||||||
|
} = useForm<AssetFormValues>({
|
||||||
|
resolver: zodResolver(assetSchema),
|
||||||
|
defaultValues: {
|
||||||
|
asset_code: "",
|
||||||
|
serial_no: "",
|
||||||
|
name: "",
|
||||||
|
category_id: 0,
|
||||||
|
department_id: 0,
|
||||||
|
location_id: 0,
|
||||||
|
supplier_id: "",
|
||||||
|
purchase_value: "",
|
||||||
|
purchase_date: "",
|
||||||
|
installation_date: "",
|
||||||
|
status: "in_service",
|
||||||
|
criticality: "non_critical",
|
||||||
|
requires_calibration: false,
|
||||||
|
insurance_applicable: false,
|
||||||
|
remarks: "",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!open) return;
|
||||||
|
setServerError(null);
|
||||||
|
if (editing) {
|
||||||
|
reset({
|
||||||
|
asset_code: editing.asset_code,
|
||||||
|
serial_no: editing.serial_no ?? "",
|
||||||
|
name: editing.name,
|
||||||
|
category_id: editing.category_id,
|
||||||
|
department_id: editing.department_id,
|
||||||
|
location_id: editing.location_id,
|
||||||
|
supplier_id: editing.supplier_id ? String(editing.supplier_id) : "",
|
||||||
|
purchase_value: editing.purchase_value != null ? String(editing.purchase_value) : "",
|
||||||
|
purchase_date: editing.purchase_date ?? "",
|
||||||
|
installation_date: editing.installation_date ?? "",
|
||||||
|
status: editing.status,
|
||||||
|
criticality: editing.criticality,
|
||||||
|
requires_calibration: editing.requires_calibration,
|
||||||
|
insurance_applicable: editing.insurance_applicable,
|
||||||
|
remarks: editing.remarks ?? "",
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
reset({
|
||||||
|
asset_code: "",
|
||||||
|
serial_no: "",
|
||||||
|
name: "",
|
||||||
|
category_id: categories[0]?.id ?? 0,
|
||||||
|
department_id: defaultDeptId,
|
||||||
|
location_id: defaultLocId,
|
||||||
|
supplier_id: "",
|
||||||
|
purchase_value: "",
|
||||||
|
purchase_date: "",
|
||||||
|
installation_date: "",
|
||||||
|
status: "in_service",
|
||||||
|
criticality: "non_critical",
|
||||||
|
requires_calibration: false,
|
||||||
|
insurance_applicable: false,
|
||||||
|
remarks: "",
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}, [open, editing, categories.length, defaultDeptId, defaultLocId, reset]);
|
||||||
|
|
||||||
|
const watchedDeptId = Number(watch("department_id"));
|
||||||
|
const filteredLocations = useMemo(
|
||||||
|
() => allLocations.filter((l) => l.department_id === watchedDeptId),
|
||||||
|
[allLocations, watchedDeptId]
|
||||||
|
);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!open || coordinatorOnly) return;
|
||||||
|
const currentLoc = Number(watch("location_id"));
|
||||||
|
if (
|
||||||
|
watchedDeptId > 0 &&
|
||||||
|
filteredLocations.length > 0 &&
|
||||||
|
!filteredLocations.some((l) => l.id === currentLoc)
|
||||||
|
) {
|
||||||
|
setValue("location_id", filteredLocations[0].id);
|
||||||
|
} else if (watchedDeptId > 0 && filteredLocations.length === 0 && currentLoc !== 0) {
|
||||||
|
setValue("location_id", 0);
|
||||||
|
}
|
||||||
|
}, [watchedDeptId, filteredLocations, open, coordinatorOnly, setValue, watch]);
|
||||||
|
|
||||||
|
async function onSubmit(values: AssetFormValues) {
|
||||||
|
setServerError(null);
|
||||||
|
try {
|
||||||
|
if (editing && coordinatorOnly) {
|
||||||
|
await assetsApi.update(editing.id, {
|
||||||
|
requires_calibration: values.requires_calibration,
|
||||||
|
insurance_applicable: values.insurance_applicable,
|
||||||
|
remarks: values.remarks?.trim() || null,
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
const payload = {
|
||||||
|
asset_code: values.asset_code.trim(),
|
||||||
|
serial_no: values.serial_no.trim(),
|
||||||
|
name: values.name.trim(),
|
||||||
|
category_id: values.category_id,
|
||||||
|
department_id: values.department_id,
|
||||||
|
location_id: values.location_id,
|
||||||
|
supplier_id: values.supplier_id ? Number(values.supplier_id) : null,
|
||||||
|
purchase_value:
|
||||||
|
values.purchase_value && values.purchase_value.trim() !== ""
|
||||||
|
? Number(values.purchase_value)
|
||||||
|
: null,
|
||||||
|
purchase_date: values.purchase_date || null,
|
||||||
|
installation_date: values.installation_date || null,
|
||||||
|
status: values.status as AssetStatus,
|
||||||
|
criticality: values.criticality as AssetCriticality,
|
||||||
|
requires_calibration: values.requires_calibration,
|
||||||
|
insurance_applicable: values.insurance_applicable,
|
||||||
|
remarks: values.remarks?.trim() || null,
|
||||||
|
};
|
||||||
|
if (editing) {
|
||||||
|
await assetsApi.update(editing.id, payload);
|
||||||
|
} else {
|
||||||
|
await assetsApi.create(payload);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
await qc.invalidateQueries({ queryKey: ["assets"] });
|
||||||
|
if (editing) {
|
||||||
|
await qc.invalidateQueries({ queryKey: ["asset-overview", editing.id] });
|
||||||
|
}
|
||||||
|
onClose();
|
||||||
|
} catch (err) {
|
||||||
|
setServerError(err instanceof ApiError ? err.detail : "Failed to save asset.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<Modal
|
||||||
|
open={open}
|
||||||
|
onOpenChange={(o) => !o && onClose()}
|
||||||
|
title={editing ? `Edit Asset — ${editing.asset_code}` : "Add New Asset"}
|
||||||
|
className="max-w-2xl"
|
||||||
|
>
|
||||||
|
{coordinatorOnly && (
|
||||||
|
<div className="mb-3 rounded-md bg-blue-50 border border-blue-200 px-3 py-2 text-xs text-blue-800">
|
||||||
|
Coordinator permissions: only calibration requirement, insurance applicability, and remarks can be edited.
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{serverError && (
|
||||||
|
<div className="mb-3 flex items-start gap-2 rounded-md bg-red-50 border border-red-200 px-3 py-2 text-sm text-red-700">
|
||||||
|
<AlertCircle className="h-4 w-4 shrink-0 mt-0.5" />
|
||||||
|
<span>{serverError}</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<form onSubmit={handleSubmit(onSubmit)} className="space-y-4">
|
||||||
|
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
|
||||||
|
<div>
|
||||||
|
<label className={labelCls}>Asset Code *</label>
|
||||||
|
<input
|
||||||
|
{...register("asset_code")}
|
||||||
|
disabled={coordinatorOnly}
|
||||||
|
placeholder="e.g. PHRC-ICU-0099"
|
||||||
|
className={inputCls}
|
||||||
|
/>
|
||||||
|
{errors.asset_code && <p className={errCls}>{errors.asset_code.message}</p>}
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className={labelCls}>Serial No *</label>
|
||||||
|
<input
|
||||||
|
{...register("serial_no")}
|
||||||
|
disabled={coordinatorOnly}
|
||||||
|
placeholder="Manufacturer serial number"
|
||||||
|
className={inputCls}
|
||||||
|
/>
|
||||||
|
{errors.serial_no && <p className={errCls}>{errors.serial_no.message}</p>}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
|
||||||
|
<div>
|
||||||
|
<label className={labelCls}>Equipment Name *</label>
|
||||||
|
<input
|
||||||
|
{...register("name")}
|
||||||
|
disabled={coordinatorOnly}
|
||||||
|
placeholder="e.g. Multipara Patient Monitor"
|
||||||
|
className={inputCls}
|
||||||
|
/>
|
||||||
|
{errors.name && <p className={errCls}>{errors.name.message}</p>}
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className={labelCls}>Category *</label>
|
||||||
|
<select {...register("category_id")} disabled={coordinatorOnly} className={inputCls}>
|
||||||
|
<option value={0}>Select category...</option>
|
||||||
|
{categories.map((c) => (
|
||||||
|
<option key={c.id} value={c.id}>
|
||||||
|
{c.name}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
{errors.category_id && <p className={errCls}>{errors.category_id.message}</p>}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
|
||||||
|
<div>
|
||||||
|
<label className={labelCls}>Department *</label>
|
||||||
|
<select {...register("department_id")} disabled={coordinatorOnly} className={inputCls}>
|
||||||
|
<option value={0}>Select department...</option>
|
||||||
|
{departments.map((d) => (
|
||||||
|
<option key={d.id} value={d.id}>
|
||||||
|
{d.name} ({d.code})
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
{errors.department_id && <p className={errCls}>{errors.department_id.message}</p>}
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className={labelCls}>Location *</label>
|
||||||
|
<select {...register("location_id")} disabled={coordinatorOnly} className={inputCls}>
|
||||||
|
<option value={0}>
|
||||||
|
{filteredLocations.length === 0 ? "No locations in department" : "Select location..."}
|
||||||
|
</option>
|
||||||
|
{filteredLocations.map((l) => (
|
||||||
|
<option key={l.id} value={l.id}>
|
||||||
|
{l.name}
|
||||||
|
{l.floor_wing ? ` (${l.floor_wing})` : ""}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
{errors.location_id && <p className={errCls}>{errors.location_id.message}</p>}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
|
||||||
|
<div>
|
||||||
|
<label className={labelCls}>Supplier</label>
|
||||||
|
<select {...register("supplier_id")} disabled={coordinatorOnly} className={inputCls}>
|
||||||
|
<option value="">None / Not specified</option>
|
||||||
|
{vendors.map((v) => (
|
||||||
|
<option key={v.id} value={String(v.id)}>
|
||||||
|
{v.name}
|
||||||
|
</option>
|
||||||
|
))}
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className={labelCls}>Purchase Value (INR)</label>
|
||||||
|
<input
|
||||||
|
type="number"
|
||||||
|
step="1"
|
||||||
|
min="0"
|
||||||
|
{...register("purchase_value")}
|
||||||
|
disabled={coordinatorOnly}
|
||||||
|
placeholder="e.g. 450000"
|
||||||
|
className={inputCls}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
|
||||||
|
<div>
|
||||||
|
<label className={labelCls}>Purchase Date</label>
|
||||||
|
<input
|
||||||
|
type="date"
|
||||||
|
{...register("purchase_date")}
|
||||||
|
disabled={coordinatorOnly}
|
||||||
|
className={inputCls}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className={labelCls}>Installation Date</label>
|
||||||
|
<input
|
||||||
|
type="date"
|
||||||
|
{...register("installation_date")}
|
||||||
|
disabled={coordinatorOnly}
|
||||||
|
className={inputCls}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid grid-cols-1 sm:grid-cols-2 gap-3">
|
||||||
|
<div>
|
||||||
|
<label className={labelCls}>Status *</label>
|
||||||
|
<select {...register("status")} disabled={coordinatorOnly} className={inputCls}>
|
||||||
|
<option value="in_service">In Service</option>
|
||||||
|
<option value="under_repair">Under Repair</option>
|
||||||
|
<option value="out_of_service">Out of Service</option>
|
||||||
|
<option value="condemned">Condemned</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<label className={labelCls}>Criticality *</label>
|
||||||
|
<select {...register("criticality")} disabled={coordinatorOnly} className={inputCls}>
|
||||||
|
<option value="critical">Critical</option>
|
||||||
|
<option value="non_critical">Non-Critical</option>
|
||||||
|
</select>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex flex-wrap gap-6 pt-1">
|
||||||
|
<label className="inline-flex items-center gap-2 text-sm text-gray-700 cursor-pointer">
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
{...register("requires_calibration")}
|
||||||
|
className="h-4 w-4 rounded border-gray-300 text-[#1e3a8a]"
|
||||||
|
/>
|
||||||
|
Requires Calibration
|
||||||
|
</label>
|
||||||
|
<label className="inline-flex items-center gap-2 text-sm text-gray-700 cursor-pointer">
|
||||||
|
<input
|
||||||
|
type="checkbox"
|
||||||
|
{...register("insurance_applicable")}
|
||||||
|
className="h-4 w-4 rounded border-gray-300 text-[#1e3a8a]"
|
||||||
|
/>
|
||||||
|
Insurance Applicable
|
||||||
|
</label>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div>
|
||||||
|
<label className={labelCls}>Remarks</label>
|
||||||
|
<textarea {...register("remarks")} rows={2} className={inputCls} />
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex justify-end gap-2 pt-2">
|
||||||
|
<Button type="button" variant="outline" onClick={onClose}>
|
||||||
|
Cancel
|
||||||
|
</Button>
|
||||||
|
<Button type="submit" loading={isSubmitting}>
|
||||||
|
{editing ? "Save Changes" : "Create Asset"}
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
</form>
|
||||||
|
</Modal>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,229 @@
|
|||||||
|
import { useState, useEffect, useRef } from "react";
|
||||||
|
import { Search, X, ShieldCheck, Ban } from "lucide-react";
|
||||||
|
import { assetsApi, type AssetLookupItem } from "@/api/assets";
|
||||||
|
import { formatDate } from "@/lib/format";
|
||||||
|
import { CoverageBadge, AssetStatusBadge } from "./StatusBadge";
|
||||||
|
|
||||||
|
interface AssetPickerProps {
|
||||||
|
selectedAsset: AssetLookupItem | null;
|
||||||
|
onSelect: (asset: AssetLookupItem | null) => void;
|
||||||
|
departmentId?: number;
|
||||||
|
disabled?: boolean;
|
||||||
|
placeholder?: string;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function AssetPicker({
|
||||||
|
selectedAsset,
|
||||||
|
onSelect,
|
||||||
|
departmentId,
|
||||||
|
disabled = false,
|
||||||
|
placeholder = "Search by asset code, equipment name, or serial no...",
|
||||||
|
}: AssetPickerProps) {
|
||||||
|
const [query, setQuery] = useState("");
|
||||||
|
const [debouncedQuery, setDebouncedQuery] = useState("");
|
||||||
|
const [results, setResults] = useState<AssetLookupItem[]>([]);
|
||||||
|
const [loading, setLoading] = useState(false);
|
||||||
|
const [open, setOpen] = useState(false);
|
||||||
|
const containerRef = useRef<HTMLDivElement>(null);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
const timer = setTimeout(() => {
|
||||||
|
setDebouncedQuery(query);
|
||||||
|
}, 250);
|
||||||
|
return () => clearTimeout(timer);
|
||||||
|
}, [query]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
if (!open || disabled) return;
|
||||||
|
let cancelled = false;
|
||||||
|
setLoading(true);
|
||||||
|
assetsApi
|
||||||
|
.lookup({ q: debouncedQuery, department_id: departmentId, limit: 25 })
|
||||||
|
.then((res) => {
|
||||||
|
if (!cancelled) setResults(res.items);
|
||||||
|
})
|
||||||
|
.catch(() => {
|
||||||
|
if (!cancelled) setResults([]);
|
||||||
|
})
|
||||||
|
.finally(() => {
|
||||||
|
if (!cancelled) setLoading(false);
|
||||||
|
});
|
||||||
|
return () => {
|
||||||
|
cancelled = true;
|
||||||
|
};
|
||||||
|
}, [debouncedQuery, departmentId, open, disabled]);
|
||||||
|
|
||||||
|
useEffect(() => {
|
||||||
|
function handleOutsideClick(e: MouseEvent) {
|
||||||
|
if (containerRef.current && !containerRef.current.contains(e.target as Node)) {
|
||||||
|
setOpen(false);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
document.addEventListener("mousedown", handleOutsideClick);
|
||||||
|
return () => document.removeEventListener("mousedown", handleOutsideClick);
|
||||||
|
}, []);
|
||||||
|
|
||||||
|
if (selectedAsset) {
|
||||||
|
const isUnderWarranty =
|
||||||
|
selectedAsset.warranty_status === "active" || selectedAsset.warranty_status === "expiring";
|
||||||
|
const isCondemned = selectedAsset.status === "condemned";
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="rounded-lg border border-blue-200 bg-blue-50/40 p-4 space-y-3">
|
||||||
|
<div className="flex items-start justify-between gap-2">
|
||||||
|
<div>
|
||||||
|
<div className="flex items-center gap-2 flex-wrap">
|
||||||
|
<span className="font-mono text-sm font-bold text-[#1e3a8a]">
|
||||||
|
{selectedAsset.asset_code}
|
||||||
|
</span>
|
||||||
|
<span className="font-semibold text-gray-900">{selectedAsset.name}</span>
|
||||||
|
<AssetStatusBadge status={selectedAsset.status} />
|
||||||
|
{isUnderWarranty && (
|
||||||
|
<span className="inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-xs font-medium bg-emerald-100 text-emerald-800 border border-emerald-300">
|
||||||
|
<ShieldCheck className="h-3 w-3" />
|
||||||
|
Under Warranty
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
{isCondemned && (
|
||||||
|
<span className="inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800 border border-red-300">
|
||||||
|
<Ban className="h-3 w-3" />
|
||||||
|
Condemned Asset
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
{selectedAsset.serial_no && (
|
||||||
|
<div className="text-xs text-gray-500 mt-0.5">
|
||||||
|
Serial No: <span className="font-mono">{selectedAsset.serial_no}</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
{!disabled && (
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => {
|
||||||
|
onSelect(null);
|
||||||
|
setQuery("");
|
||||||
|
}}
|
||||||
|
aria-label="Clear selected asset"
|
||||||
|
className="inline-flex items-center gap-1 text-xs text-gray-600 hover:text-gray-900 px-2 py-1 rounded border border-gray-200 bg-white"
|
||||||
|
>
|
||||||
|
<X className="h-3.5 w-3.5" />
|
||||||
|
Change
|
||||||
|
</button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid grid-cols-2 sm:grid-cols-3 gap-3 text-xs">
|
||||||
|
<div>
|
||||||
|
<div className="text-gray-500">Category</div>
|
||||||
|
<div className="font-medium text-gray-800">{selectedAsset.category_name || "—"}</div>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<div className="text-gray-500">Department</div>
|
||||||
|
<div className="font-medium text-gray-800">{selectedAsset.department_name || "—"}</div>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<div className="text-gray-500">Location</div>
|
||||||
|
<div className="font-medium text-gray-800">{selectedAsset.location_name || "—"}</div>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<div className="text-gray-500">Warranty</div>
|
||||||
|
<div className="mt-0.5 flex items-center gap-1.5 flex-wrap">
|
||||||
|
<CoverageBadge status={selectedAsset.warranty_status} />
|
||||||
|
{selectedAsset.warranty_end_date && (
|
||||||
|
<span className="text-gray-600">
|
||||||
|
till {formatDate(selectedAsset.warranty_end_date)}
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<div className="text-gray-500">Contract</div>
|
||||||
|
<div className="font-medium text-gray-800">
|
||||||
|
{selectedAsset.contract_summary ||
|
||||||
|
(selectedAsset.contract_type
|
||||||
|
? `${selectedAsset.contract_type} (${selectedAsset.contract_status})`
|
||||||
|
: "None")}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<div className="text-gray-500">Insurance</div>
|
||||||
|
<div className="font-medium text-gray-800">
|
||||||
|
{selectedAsset.insurance_summary || selectedAsset.insurance_status || "None"}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div ref={containerRef} className="relative">
|
||||||
|
<div className="relative">
|
||||||
|
<Search className="absolute left-3 top-1/2 -translate-y-1/2 h-4 w-4 text-gray-400" />
|
||||||
|
<input
|
||||||
|
type="text"
|
||||||
|
disabled={disabled}
|
||||||
|
value={query}
|
||||||
|
onFocus={() => setOpen(true)}
|
||||||
|
onChange={(e) => {
|
||||||
|
setQuery(e.target.value);
|
||||||
|
setOpen(true);
|
||||||
|
}}
|
||||||
|
placeholder={placeholder}
|
||||||
|
className="w-full pl-9 pr-4 py-2 text-sm border border-gray-300 rounded-md focus:outline-none focus:ring-2 focus:ring-blue-500 bg-white disabled:bg-gray-100"
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{open && !disabled && (
|
||||||
|
<div className="absolute left-0 right-0 mt-1 max-h-72 overflow-y-auto bg-white border border-gray-200 rounded-md shadow-lg z-30 divide-y divide-gray-100">
|
||||||
|
{loading ? (
|
||||||
|
<div className="px-4 py-3 text-xs text-gray-500">Searching assets...</div>
|
||||||
|
) : results.length === 0 ? (
|
||||||
|
<div className="px-4 py-3 text-xs text-gray-500">No matching assets found.</div>
|
||||||
|
) : (
|
||||||
|
results.map((item) => {
|
||||||
|
const underWarranty =
|
||||||
|
item.warranty_status === "active" || item.warranty_status === "expiring";
|
||||||
|
const condemned = item.status === "condemned";
|
||||||
|
return (
|
||||||
|
<button
|
||||||
|
key={item.id}
|
||||||
|
type="button"
|
||||||
|
onClick={() => {
|
||||||
|
onSelect(item);
|
||||||
|
setOpen(false);
|
||||||
|
}}
|
||||||
|
className="w-full text-left px-3 py-2.5 hover:bg-blue-50/60 transition-colors flex items-center justify-between gap-2"
|
||||||
|
>
|
||||||
|
<div className="min-w-0">
|
||||||
|
<div className="text-sm font-medium text-gray-900 truncate">
|
||||||
|
<span className="font-mono text-[#1e3a8a]">{item.asset_code}</span> —{" "}
|
||||||
|
{item.name}
|
||||||
|
{item.serial_no ? ` (${item.serial_no})` : ""}
|
||||||
|
</div>
|
||||||
|
<div className="text-xs text-gray-500 truncate">
|
||||||
|
{item.department_name || "—"} • {item.location_name || "—"}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div className="flex items-center gap-1.5 shrink-0">
|
||||||
|
{underWarranty && (
|
||||||
|
<span className="px-2 py-0.5 rounded-full text-[11px] font-medium bg-emerald-100 text-emerald-800">
|
||||||
|
Under Warranty
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
{condemned && (
|
||||||
|
<span className="px-2 py-0.5 rounded-full text-[11px] font-medium bg-red-100 text-red-800">
|
||||||
|
Condemned
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
})
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,285 @@
|
|||||||
|
import { useState, useRef } from "react";
|
||||||
|
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
|
||||||
|
import {
|
||||||
|
Upload,
|
||||||
|
FileText,
|
||||||
|
Image as ImageIcon,
|
||||||
|
Download,
|
||||||
|
Trash2,
|
||||||
|
AlertCircle,
|
||||||
|
ExternalLink,
|
||||||
|
} from "lucide-react";
|
||||||
|
import {
|
||||||
|
attachmentsApi,
|
||||||
|
type AttachmentEntityType,
|
||||||
|
type AttachmentItem,
|
||||||
|
} from "@/api/attachments";
|
||||||
|
import { ApiError } from "@/api/client";
|
||||||
|
import { formatDateTime } from "@/lib/format";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
|
||||||
|
const MAX_SIZE_BYTES = 10 * 1024 * 1024; // 10 MB
|
||||||
|
const ALLOWED_EXTENSIONS = [".jpg", ".jpeg", ".png", ".pdf"];
|
||||||
|
const ALLOWED_MIME_TYPES = ["image/jpeg", "image/png", "application/pdf"];
|
||||||
|
|
||||||
|
export function validateAttachmentFile(file: File): string | null {
|
||||||
|
const nameLower = file.name.toLowerCase();
|
||||||
|
const hasAllowedExt = ALLOWED_EXTENSIONS.some((ext) => nameLower.endsWith(ext));
|
||||||
|
const hasAllowedMime = !file.type || ALLOWED_MIME_TYPES.includes(file.type);
|
||||||
|
|
||||||
|
if (!hasAllowedExt || !hasAllowedMime) {
|
||||||
|
return "Invalid file type. Only JPG, PNG, and PDF files are allowed.";
|
||||||
|
}
|
||||||
|
if (file.size > MAX_SIZE_BYTES) {
|
||||||
|
return "File is too large. Maximum allowed size is 10 MB.";
|
||||||
|
}
|
||||||
|
return null;
|
||||||
|
}
|
||||||
|
|
||||||
|
function formatBytes(bytes: number): string {
|
||||||
|
if (bytes < 1024) return `${bytes} B`;
|
||||||
|
if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(1)} KB`;
|
||||||
|
return `${(bytes / (1024 * 1024)).toFixed(2)} MB`;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface AttachmentsProps {
|
||||||
|
entityType: AttachmentEntityType;
|
||||||
|
entityId: number;
|
||||||
|
canUpload: boolean;
|
||||||
|
canDelete: boolean;
|
||||||
|
}
|
||||||
|
|
||||||
|
export function Attachments({
|
||||||
|
entityType,
|
||||||
|
entityId,
|
||||||
|
canUpload,
|
||||||
|
canDelete,
|
||||||
|
}: AttachmentsProps) {
|
||||||
|
const qc = useQueryClient();
|
||||||
|
const fileInputRef = useRef<HTMLInputElement>(null);
|
||||||
|
const [dragActive, setDragActive] = useState(false);
|
||||||
|
const [errorMsg, setErrorMsg] = useState<string | null>(null);
|
||||||
|
const [confirmDeleteId, setConfirmDeleteId] = useState<number | null>(null);
|
||||||
|
|
||||||
|
const queryKey = ["attachments", entityType, entityId];
|
||||||
|
|
||||||
|
const { data, isLoading } = useQuery({
|
||||||
|
queryKey,
|
||||||
|
queryFn: () => attachmentsApi.list(entityType, entityId),
|
||||||
|
enabled: Boolean(entityId),
|
||||||
|
});
|
||||||
|
|
||||||
|
const uploadMutation = useMutation({
|
||||||
|
mutationFn: (file: File) => attachmentsApi.upload(entityType, entityId, file),
|
||||||
|
onSuccess: () => {
|
||||||
|
setErrorMsg(null);
|
||||||
|
qc.invalidateQueries({ queryKey });
|
||||||
|
if (entityType === "asset") {
|
||||||
|
qc.invalidateQueries({ queryKey: ["asset-overview", entityId] });
|
||||||
|
}
|
||||||
|
},
|
||||||
|
onError: (err) => {
|
||||||
|
setErrorMsg(err instanceof ApiError ? err.detail : "Failed to upload attachment.");
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const deleteMutation = useMutation({
|
||||||
|
mutationFn: (id: number) => attachmentsApi.remove(id),
|
||||||
|
onSuccess: () => {
|
||||||
|
setConfirmDeleteId(null);
|
||||||
|
setErrorMsg(null);
|
||||||
|
qc.invalidateQueries({ queryKey });
|
||||||
|
if (entityType === "asset") {
|
||||||
|
qc.invalidateQueries({ queryKey: ["asset-overview", entityId] });
|
||||||
|
}
|
||||||
|
},
|
||||||
|
onError: (err) => {
|
||||||
|
setErrorMsg(err instanceof ApiError ? err.detail : "Failed to delete attachment.");
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
function handleFiles(files: FileList | null) {
|
||||||
|
if (!files || files.length === 0) return;
|
||||||
|
const file = files[0];
|
||||||
|
const validationError = validateAttachmentFile(file);
|
||||||
|
if (validationError) {
|
||||||
|
setErrorMsg(validationError);
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
setErrorMsg(null);
|
||||||
|
uploadMutation.mutate(file);
|
||||||
|
}
|
||||||
|
|
||||||
|
async function handleDownload(att: AttachmentItem, preview = false) {
|
||||||
|
try {
|
||||||
|
setErrorMsg(null);
|
||||||
|
await attachmentsApi.download(att.id, att.original_name, preview);
|
||||||
|
} catch (err) {
|
||||||
|
setErrorMsg(err instanceof ApiError ? err.detail : "Failed to download file.");
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const items = data?.items ?? [];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-4">
|
||||||
|
{errorMsg && (
|
||||||
|
<div
|
||||||
|
role="alert"
|
||||||
|
className="flex items-start gap-2 rounded-md bg-red-50 border border-red-200 px-3 py-2 text-sm text-red-700"
|
||||||
|
>
|
||||||
|
<AlertCircle className="h-4 w-4 shrink-0 mt-0.5" />
|
||||||
|
<span>{errorMsg}</span>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{canUpload && (
|
||||||
|
<div
|
||||||
|
onDragOver={(e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
setDragActive(true);
|
||||||
|
}}
|
||||||
|
onDragLeave={() => setDragActive(false)}
|
||||||
|
onDrop={(e) => {
|
||||||
|
e.preventDefault();
|
||||||
|
setDragActive(false);
|
||||||
|
handleFiles(e.dataTransfer.files);
|
||||||
|
}}
|
||||||
|
className={`border-2 border-dashed rounded-lg p-5 text-center transition-colors ${
|
||||||
|
dragActive
|
||||||
|
? "border-[#1e3a8a] bg-blue-50/50"
|
||||||
|
: "border-gray-300 bg-gray-50/50 hover:border-gray-400"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
<input
|
||||||
|
ref={fileInputRef}
|
||||||
|
type="file"
|
||||||
|
accept=".jpg,.jpeg,.png,.pdf"
|
||||||
|
aria-label="Upload attachment"
|
||||||
|
className="hidden"
|
||||||
|
onChange={(e) => {
|
||||||
|
handleFiles(e.target.files);
|
||||||
|
e.target.value = "";
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
<Upload className="h-6 w-6 text-gray-400 mx-auto mb-2" />
|
||||||
|
<p className="text-sm text-gray-600">
|
||||||
|
Drag and drop a file here, or{" "}
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => fileInputRef.current?.click()}
|
||||||
|
disabled={uploadMutation.isPending}
|
||||||
|
className="text-[#1e3a8a] font-medium hover:underline disabled:opacity-50"
|
||||||
|
>
|
||||||
|
browse
|
||||||
|
</button>
|
||||||
|
</p>
|
||||||
|
<p className="text-xs text-gray-400 mt-1">
|
||||||
|
Allowed: JPG, PNG, PDF • Max size: 10 MB
|
||||||
|
</p>
|
||||||
|
{uploadMutation.isPending && (
|
||||||
|
<p className="text-xs text-blue-600 mt-2">Uploading...</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{isLoading ? (
|
||||||
|
<div className="space-y-2">
|
||||||
|
{[1, 2].map((i) => (
|
||||||
|
<div key={i} className="h-14 bg-gray-100 rounded-md animate-pulse" />
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
) : items.length === 0 ? (
|
||||||
|
<div className="text-sm text-gray-400 py-6 text-center border border-gray-200 rounded-lg bg-white">
|
||||||
|
No attachments uploaded yet.
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<div className="bg-white border border-gray-200 rounded-lg divide-y divide-gray-100">
|
||||||
|
{items.map((att) => {
|
||||||
|
const isPdf = att.mime_type === "application/pdf";
|
||||||
|
return (
|
||||||
|
<div
|
||||||
|
key={att.id}
|
||||||
|
className="flex items-center justify-between gap-3 px-4 py-3 hover:bg-gray-50/60"
|
||||||
|
>
|
||||||
|
<div className="flex items-center gap-3 min-w-0">
|
||||||
|
<div className="h-9 w-9 rounded-md bg-blue-50 text-[#1e3a8a] flex items-center justify-center shrink-0">
|
||||||
|
{isPdf ? <FileText className="h-5 w-5" /> : <ImageIcon className="h-5 w-5" />}
|
||||||
|
</div>
|
||||||
|
<div className="min-w-0">
|
||||||
|
<div className="text-sm font-medium text-gray-900 truncate">
|
||||||
|
{att.original_name}
|
||||||
|
</div>
|
||||||
|
<div className="text-xs text-gray-500">
|
||||||
|
{formatBytes(att.size_bytes)}
|
||||||
|
{att.uploaded_by_name ? ` • Uploaded by ${att.uploaded_by_name}` : ""}
|
||||||
|
{" • "}
|
||||||
|
{formatDateTime(att.uploaded_at)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="flex items-center gap-1.5 shrink-0">
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
onClick={() => handleDownload(att, true)}
|
||||||
|
title="Preview in new tab"
|
||||||
|
>
|
||||||
|
<ExternalLink className="h-3.5 w-3.5 mr-1" />
|
||||||
|
Preview
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="outline"
|
||||||
|
size="sm"
|
||||||
|
onClick={() => handleDownload(att, false)}
|
||||||
|
title="Download file"
|
||||||
|
>
|
||||||
|
<Download className="h-3.5 w-3.5 mr-1" />
|
||||||
|
Download
|
||||||
|
</Button>
|
||||||
|
{canDelete && (
|
||||||
|
confirmDeleteId === att.id ? (
|
||||||
|
<div className="flex items-center gap-1">
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="danger"
|
||||||
|
size="sm"
|
||||||
|
loading={deleteMutation.isPending}
|
||||||
|
onClick={() => deleteMutation.mutate(att.id)}
|
||||||
|
>
|
||||||
|
Confirm
|
||||||
|
</Button>
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
onClick={() => setConfirmDeleteId(null)}
|
||||||
|
>
|
||||||
|
Cancel
|
||||||
|
</Button>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<Button
|
||||||
|
type="button"
|
||||||
|
variant="ghost"
|
||||||
|
size="sm"
|
||||||
|
className="text-red-600 hover:bg-red-50"
|
||||||
|
onClick={() => setConfirmDeleteId(att.id)}
|
||||||
|
aria-label={`Delete ${att.original_name}`}
|
||||||
|
>
|
||||||
|
<Trash2 className="h-3.5 w-3.5" />
|
||||||
|
</Button>
|
||||||
|
)
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
})}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,201 @@
|
|||||||
|
import {
|
||||||
|
CheckCircle2,
|
||||||
|
Wrench,
|
||||||
|
AlertTriangle,
|
||||||
|
Ban,
|
||||||
|
Clock,
|
||||||
|
ShieldAlert,
|
||||||
|
MinusCircle,
|
||||||
|
} from "lucide-react";
|
||||||
|
import { cn } from "@/lib/utils";
|
||||||
|
import type {
|
||||||
|
AssetStatus,
|
||||||
|
AssetCriticality,
|
||||||
|
CoverageStatus,
|
||||||
|
AlertSeverity,
|
||||||
|
CalibrationStatus,
|
||||||
|
} from "@/api/assets";
|
||||||
|
|
||||||
|
export function AssetStatusBadge({
|
||||||
|
status,
|
||||||
|
className,
|
||||||
|
}: {
|
||||||
|
status: AssetStatus | string;
|
||||||
|
className?: string;
|
||||||
|
}) {
|
||||||
|
const map: Record<string, { label: string; cls: string; dot: string; icon: React.ReactNode }> = {
|
||||||
|
in_service: {
|
||||||
|
label: "In Service",
|
||||||
|
cls: "bg-green-100 text-green-800 border border-green-200",
|
||||||
|
dot: "bg-green-600",
|
||||||
|
icon: <CheckCircle2 className="h-3 w-3 shrink-0" />,
|
||||||
|
},
|
||||||
|
under_repair: {
|
||||||
|
label: "Under Repair",
|
||||||
|
cls: "bg-red-100 text-red-800 border border-red-200",
|
||||||
|
dot: "bg-red-600",
|
||||||
|
icon: <Wrench className="h-3 w-3 shrink-0" />,
|
||||||
|
},
|
||||||
|
out_of_service: {
|
||||||
|
label: "Out of Service",
|
||||||
|
cls: "bg-amber-100 text-amber-800 border border-amber-200",
|
||||||
|
dot: "bg-amber-600",
|
||||||
|
icon: <AlertTriangle className="h-3 w-3 shrink-0" />,
|
||||||
|
},
|
||||||
|
condemned: {
|
||||||
|
label: "Condemned",
|
||||||
|
cls: "bg-gray-100 text-gray-700 border border-gray-300",
|
||||||
|
dot: "bg-gray-500",
|
||||||
|
icon: <Ban className="h-3 w-3 shrink-0" />,
|
||||||
|
},
|
||||||
|
};
|
||||||
|
|
||||||
|
const cfg = map[status] ?? {
|
||||||
|
label: status,
|
||||||
|
cls: "bg-gray-100 text-gray-700",
|
||||||
|
dot: "bg-gray-500",
|
||||||
|
icon: <MinusCircle className="h-3 w-3 shrink-0" />,
|
||||||
|
};
|
||||||
|
|
||||||
|
return (
|
||||||
|
<span
|
||||||
|
className={cn(
|
||||||
|
"inline-flex items-center gap-1.5 px-2.5 py-0.5 rounded-full text-xs font-medium whitespace-nowrap",
|
||||||
|
cfg.cls,
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{cfg.icon}
|
||||||
|
<span>{cfg.label}</span>
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function CoverageBadge({
|
||||||
|
status,
|
||||||
|
severity,
|
||||||
|
prefix,
|
||||||
|
className,
|
||||||
|
}: {
|
||||||
|
status: CoverageStatus | string;
|
||||||
|
severity?: AlertSeverity | string;
|
||||||
|
prefix?: string;
|
||||||
|
className?: string;
|
||||||
|
}) {
|
||||||
|
let cls = "bg-gray-100 text-gray-600 border border-gray-200";
|
||||||
|
let dot = "bg-gray-400";
|
||||||
|
let label = "None";
|
||||||
|
|
||||||
|
if (status === "active") {
|
||||||
|
cls = "bg-green-100 text-green-800 border border-green-200";
|
||||||
|
dot = "bg-green-600";
|
||||||
|
label = "Active";
|
||||||
|
} else if (status === "expiring") {
|
||||||
|
if (severity === "red") {
|
||||||
|
cls = "bg-red-100 text-red-800 border border-red-200";
|
||||||
|
dot = "bg-red-600";
|
||||||
|
} else {
|
||||||
|
cls = "bg-yellow-100 text-yellow-800 border border-yellow-300";
|
||||||
|
dot = "bg-yellow-500";
|
||||||
|
}
|
||||||
|
label = "Expiring";
|
||||||
|
} else if (status === "expired") {
|
||||||
|
cls = "bg-red-100 text-red-800 border border-red-200";
|
||||||
|
dot = "bg-red-600";
|
||||||
|
label = "Expired";
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<span
|
||||||
|
className={cn(
|
||||||
|
"inline-flex items-center gap-1.5 px-2.5 py-0.5 rounded-full text-xs font-medium whitespace-nowrap",
|
||||||
|
cls,
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<span className={cn("h-1.5 w-1.5 rounded-full shrink-0", dot)} />
|
||||||
|
<span>{prefix ? `${prefix}: ${label}` : label}</span>
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function CalibrationBadge({
|
||||||
|
status,
|
||||||
|
severity,
|
||||||
|
className,
|
||||||
|
}: {
|
||||||
|
status: CalibrationStatus | string;
|
||||||
|
severity?: AlertSeverity | string;
|
||||||
|
className?: string;
|
||||||
|
}) {
|
||||||
|
let cls = "bg-gray-100 text-gray-600 border border-gray-200";
|
||||||
|
let icon: React.ReactNode = <MinusCircle className="h-3 w-3 shrink-0" />;
|
||||||
|
let label = "None";
|
||||||
|
|
||||||
|
if (status === "completed") {
|
||||||
|
cls = "bg-green-100 text-green-800 border border-green-200";
|
||||||
|
icon = <CheckCircle2 className="h-3 w-3 shrink-0" />;
|
||||||
|
label = "Completed";
|
||||||
|
} else if (status === "upcoming") {
|
||||||
|
cls = "bg-blue-100 text-blue-800 border border-blue-200";
|
||||||
|
icon = <Clock className="h-3 w-3 shrink-0" />;
|
||||||
|
label = "Upcoming";
|
||||||
|
} else if (status === "due") {
|
||||||
|
cls =
|
||||||
|
severity === "red"
|
||||||
|
? "bg-red-100 text-red-800 border border-red-200"
|
||||||
|
: "bg-yellow-100 text-yellow-800 border border-yellow-300";
|
||||||
|
icon = <AlertTriangle className="h-3 w-3 shrink-0" />;
|
||||||
|
label = "Due";
|
||||||
|
} else if (status === "overdue") {
|
||||||
|
cls = "bg-red-100 text-red-800 border border-red-200";
|
||||||
|
icon = <AlertTriangle className="h-3 w-3 shrink-0" />;
|
||||||
|
label = "Overdue";
|
||||||
|
}
|
||||||
|
|
||||||
|
return (
|
||||||
|
<span
|
||||||
|
className={cn(
|
||||||
|
"inline-flex items-center gap-1.5 px-2.5 py-0.5 rounded-full text-xs font-medium whitespace-nowrap",
|
||||||
|
cls,
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
{icon}
|
||||||
|
<span>{label}</span>
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
export function CriticalityBadge({
|
||||||
|
criticality,
|
||||||
|
className,
|
||||||
|
}: {
|
||||||
|
criticality: AssetCriticality | string;
|
||||||
|
className?: string;
|
||||||
|
}) {
|
||||||
|
if (criticality === "critical") {
|
||||||
|
return (
|
||||||
|
<span
|
||||||
|
className={cn(
|
||||||
|
"inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-xs font-semibold border border-red-400 text-red-700 bg-red-50 whitespace-nowrap",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<ShieldAlert className="h-3 w-3 shrink-0" />
|
||||||
|
Critical
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<span
|
||||||
|
className={cn(
|
||||||
|
"inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-xs font-medium bg-slate-100 text-slate-700 border border-slate-200 whitespace-nowrap",
|
||||||
|
className
|
||||||
|
)}
|
||||||
|
>
|
||||||
|
<span className="h-1.5 w-1.5 rounded-full bg-slate-500 shrink-0" />
|
||||||
|
Non-Critical
|
||||||
|
</span>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,544 @@
|
|||||||
|
import { useState } from "react";
|
||||||
|
import { useParams, Link } from "react-router-dom";
|
||||||
|
import { useQuery } from "@tanstack/react-query";
|
||||||
|
import {
|
||||||
|
ArrowLeft,
|
||||||
|
Pencil,
|
||||||
|
ShieldCheck,
|
||||||
|
Ban,
|
||||||
|
AlertCircle,
|
||||||
|
} from "lucide-react";
|
||||||
|
import { assetsApi } from "@/api/assets";
|
||||||
|
import { ApiError } from "@/api/client";
|
||||||
|
import { useAuthStore } from "@/hooks/useAuth";
|
||||||
|
import { can } from "@/lib/permissions";
|
||||||
|
import { formatDate, formatDateTime, formatINR } from "@/lib/format";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import { Badge } from "@/components/ui/badge";
|
||||||
|
import {
|
||||||
|
AssetStatusBadge,
|
||||||
|
CoverageBadge,
|
||||||
|
CalibrationBadge,
|
||||||
|
CriticalityBadge,
|
||||||
|
} from "@/components/StatusBadge";
|
||||||
|
import { Attachments } from "@/components/Attachments";
|
||||||
|
import { AssetFormModal } from "@/components/AssetFormModal";
|
||||||
|
|
||||||
|
type DetailTab =
|
||||||
|
| "overview"
|
||||||
|
| "warranty"
|
||||||
|
| "contracts"
|
||||||
|
| "insurance"
|
||||||
|
| "calibration"
|
||||||
|
| "pm"
|
||||||
|
| "breakdowns"
|
||||||
|
| "documents";
|
||||||
|
|
||||||
|
const DETAIL_TABS: { key: DetailTab; label: string }[] = [
|
||||||
|
{ key: "overview", label: "Overview" },
|
||||||
|
{ key: "warranty", label: "Warranty" },
|
||||||
|
{ key: "contracts", label: "AMC/CMC" },
|
||||||
|
{ key: "insurance", label: "Insurance" },
|
||||||
|
{ key: "calibration", label: "Calibration" },
|
||||||
|
{ key: "pm", label: "Preventive Maintenance" },
|
||||||
|
{ key: "breakdowns", label: "Breakdowns" },
|
||||||
|
{ key: "documents", label: "Documents" },
|
||||||
|
];
|
||||||
|
|
||||||
|
export function AssetDetailPage() {
|
||||||
|
const { id } = useParams<{ id: string }>();
|
||||||
|
const assetId = Number(id);
|
||||||
|
const role = useAuthStore((s) => s.user?.role);
|
||||||
|
|
||||||
|
const [activeTab, setActiveTab] = useState<DetailTab>("overview");
|
||||||
|
const [editOpen, setEditOpen] = useState(false);
|
||||||
|
|
||||||
|
const canFullEdit = can(role, "create_edit_assets");
|
||||||
|
const canContractOnlyEdit = !canFullEdit && can(role, "edit_asset_contracts_only");
|
||||||
|
const canEdit = canFullEdit || canContractOnlyEdit;
|
||||||
|
|
||||||
|
const { data, isLoading, isError, error } = useQuery({
|
||||||
|
queryKey: ["asset-overview", assetId],
|
||||||
|
queryFn: () => assetsApi.overview(assetId),
|
||||||
|
enabled: Number.isFinite(assetId) && assetId > 0,
|
||||||
|
});
|
||||||
|
|
||||||
|
if (isLoading) {
|
||||||
|
return (
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div className="h-8 w-40 bg-gray-200 rounded animate-pulse" />
|
||||||
|
<div className="h-40 bg-white border border-gray-200 rounded-lg animate-pulse" />
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
if (isError || !data) {
|
||||||
|
return (
|
||||||
|
<div className="max-w-lg mx-auto mt-10 bg-white border border-red-200 rounded-lg p-6 text-center space-y-3">
|
||||||
|
<AlertCircle className="h-8 w-8 text-red-500 mx-auto" />
|
||||||
|
<h2 className="text-lg font-semibold text-gray-900">Unable to load asset</h2>
|
||||||
|
<p className="text-sm text-red-600">
|
||||||
|
{error instanceof ApiError ? error.detail : "Asset not found or access denied."}
|
||||||
|
</p>
|
||||||
|
<Link to="/assets">
|
||||||
|
<Button variant="outline">Back to Assets</Button>
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
const {
|
||||||
|
asset,
|
||||||
|
warranties,
|
||||||
|
contracts,
|
||||||
|
insurance_policies,
|
||||||
|
calibration_plan,
|
||||||
|
calibration_records,
|
||||||
|
pm_schedules,
|
||||||
|
pm_records,
|
||||||
|
complaints,
|
||||||
|
} = data;
|
||||||
|
|
||||||
|
const isUnderWarranty =
|
||||||
|
asset.warranty_status === "active" || asset.warranty_status === "expiring";
|
||||||
|
const isCondemned = asset.status === "condemned";
|
||||||
|
const openComplaintsCount = complaints.filter((c) => c.call_status !== "closed").length;
|
||||||
|
const latestPm = pm_records[0];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-5">
|
||||||
|
<div>
|
||||||
|
<Link
|
||||||
|
to="/assets"
|
||||||
|
className="inline-flex items-center gap-1.5 text-sm text-gray-500 hover:text-gray-800"
|
||||||
|
>
|
||||||
|
<ArrowLeft className="h-4 w-4" />
|
||||||
|
Back to Asset Register
|
||||||
|
</Link>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Header Card */}
|
||||||
|
<div className="bg-white rounded-xl border border-gray-200 p-5 sm:p-6 shadow-sm space-y-4">
|
||||||
|
<div className="flex flex-wrap items-start justify-between gap-4">
|
||||||
|
<div className="space-y-1.5">
|
||||||
|
<div className="flex items-center gap-2.5 flex-wrap">
|
||||||
|
<span className="font-mono text-sm font-bold px-2.5 py-0.5 rounded bg-blue-50 text-[#1e3a8a] border border-blue-200">
|
||||||
|
{asset.asset_code}
|
||||||
|
</span>
|
||||||
|
<AssetStatusBadge status={asset.status} />
|
||||||
|
<CriticalityBadge criticality={asset.criticality} />
|
||||||
|
{isUnderWarranty && (
|
||||||
|
<span className="inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-xs font-medium bg-emerald-100 text-emerald-800 border border-emerald-300">
|
||||||
|
<ShieldCheck className="h-3.5 w-3.5" />
|
||||||
|
Under Warranty
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
{isCondemned && (
|
||||||
|
<span className="inline-flex items-center gap-1 px-2.5 py-0.5 rounded-full text-xs font-medium bg-red-100 text-red-800 border border-red-300">
|
||||||
|
<Ban className="h-3.5 w-3.5" />
|
||||||
|
Condemned
|
||||||
|
</span>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
<h1 className="text-2xl font-bold text-gray-900">{asset.name}</h1>
|
||||||
|
<p className="text-sm text-gray-500">
|
||||||
|
{asset.department_name || "—"} • {asset.location_name || "—"}
|
||||||
|
{asset.serial_no ? ` • Serial: ${asset.serial_no}` : ""}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{canEdit && (
|
||||||
|
<Button variant="outline" onClick={() => setEditOpen(true)}>
|
||||||
|
<Pencil className="h-4 w-4 mr-1.5" />
|
||||||
|
Edit Asset
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="grid grid-cols-2 sm:grid-cols-4 gap-4 pt-3 border-t border-gray-100 text-sm">
|
||||||
|
<div>
|
||||||
|
<div className="text-xs text-gray-500">Category</div>
|
||||||
|
<div className="font-medium text-gray-900">{asset.category_name || "—"}</div>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<div className="text-xs text-gray-500">Supplier</div>
|
||||||
|
<div className="font-medium text-gray-900">{asset.supplier_name || "—"}</div>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<div className="text-xs text-gray-500">Purchase Value</div>
|
||||||
|
<div className="font-medium text-gray-900">{formatINR(asset.purchase_value)}</div>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<div className="text-xs text-gray-500">Purchase / Installed</div>
|
||||||
|
<div className="font-medium text-gray-900">
|
||||||
|
{formatDate(asset.purchase_date)} / {formatDate(asset.installation_date)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Tabs */}
|
||||||
|
<div className="border-b border-gray-200 flex gap-1 overflow-x-auto">
|
||||||
|
{DETAIL_TABS.map((tab) => (
|
||||||
|
<button
|
||||||
|
key={tab.key}
|
||||||
|
type="button"
|
||||||
|
onClick={() => setActiveTab(tab.key)}
|
||||||
|
className={`px-4 py-2.5 text-sm font-medium border-b-2 transition-colors whitespace-nowrap ${
|
||||||
|
activeTab === tab.key
|
||||||
|
? "border-[#1e3a8a] text-[#1e3a8a]"
|
||||||
|
: "border-transparent text-gray-500 hover:text-gray-800"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{tab.label}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Tab Content */}
|
||||||
|
{activeTab === "overview" && (
|
||||||
|
<div className="space-y-5">
|
||||||
|
<div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-4">
|
||||||
|
<div className="bg-white rounded-lg border border-gray-200 p-4 space-y-1.5">
|
||||||
|
<div className="text-xs font-medium text-gray-500">Warranty</div>
|
||||||
|
<div>
|
||||||
|
<CoverageBadge status={asset.warranty_status} severity={asset.warranty_severity} />
|
||||||
|
</div>
|
||||||
|
<div className="text-xs text-gray-600">
|
||||||
|
Ends: {formatDate(asset.warranty_end_date)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="bg-white rounded-lg border border-gray-200 p-4 space-y-1.5">
|
||||||
|
<div className="text-xs font-medium text-gray-500">AMC / CMC Contract</div>
|
||||||
|
<div>
|
||||||
|
<CoverageBadge
|
||||||
|
status={asset.contract_status}
|
||||||
|
severity={asset.contract_severity}
|
||||||
|
prefix={asset.contract_type ?? undefined}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="text-xs text-gray-600">
|
||||||
|
Ends: {formatDate(asset.contract_end_date)}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="bg-white rounded-lg border border-gray-200 p-4 space-y-1.5">
|
||||||
|
<div className="text-xs font-medium text-gray-500">Insurance</div>
|
||||||
|
<div>
|
||||||
|
<CoverageBadge status={asset.insurance_status} />
|
||||||
|
</div>
|
||||||
|
<div className="text-xs text-gray-600">
|
||||||
|
{asset.insurance_applicable
|
||||||
|
? `Ends: ${formatDate(asset.insurance_end_date)}`
|
||||||
|
: "Not applicable"}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="bg-white rounded-lg border border-gray-200 p-4 space-y-1.5">
|
||||||
|
<div className="text-xs font-medium text-gray-500">Calibration</div>
|
||||||
|
<div>
|
||||||
|
<CalibrationBadge
|
||||||
|
status={asset.calibration_status}
|
||||||
|
severity={asset.calibration_severity}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div className="text-xs text-gray-600">
|
||||||
|
{asset.requires_calibration
|
||||||
|
? `Next due: ${formatDate(asset.calibration_due_date)}`
|
||||||
|
: "Not required"}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="bg-white rounded-lg border border-gray-200 p-4 space-y-1.5">
|
||||||
|
<div className="text-xs font-medium text-gray-500">Latest PM</div>
|
||||||
|
<div className="text-sm font-semibold text-gray-900">
|
||||||
|
{latestPm ? latestPm.status : "No PM records"}
|
||||||
|
</div>
|
||||||
|
<div className="text-xs text-gray-600">
|
||||||
|
{latestPm
|
||||||
|
? latestPm.completed_date
|
||||||
|
? `Completed: ${formatDate(latestPm.completed_date)}`
|
||||||
|
: `Planned: ${formatDate(latestPm.planned_date)}`
|
||||||
|
: `${pm_schedules.length} schedule(s)`}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="bg-white rounded-lg border border-gray-200 p-4 space-y-1.5">
|
||||||
|
<div className="text-xs font-medium text-gray-500">Breakdowns</div>
|
||||||
|
<div className="text-sm font-semibold text-gray-900">
|
||||||
|
{openComplaintsCount} open / {complaints.length} total
|
||||||
|
</div>
|
||||||
|
<div className="text-xs text-gray-600">Click Breakdowns tab for full history</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div className="bg-white rounded-lg border border-gray-200 p-5 space-y-3">
|
||||||
|
<h3 className="text-sm font-semibold text-gray-800">Full Asset Metadata</h3>
|
||||||
|
<dl className="grid grid-cols-1 sm:grid-cols-3 gap-4 text-sm">
|
||||||
|
<div>
|
||||||
|
<dt className="text-xs text-gray-500">Asset Code</dt>
|
||||||
|
<dd className="font-mono text-gray-900">{asset.asset_code}</dd>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<dt className="text-xs text-gray-500">Serial Number</dt>
|
||||||
|
<dd className="font-mono text-gray-900">{asset.serial_no || "—"}</dd>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<dt className="text-xs text-gray-500">Requires Calibration</dt>
|
||||||
|
<dd className="text-gray-900">{asset.requires_calibration ? "Yes" : "No"}</dd>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<dt className="text-xs text-gray-500">Insurance Applicable</dt>
|
||||||
|
<dd className="text-gray-900">{asset.insurance_applicable ? "Yes" : "No"}</dd>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<dt className="text-xs text-gray-500">Created At</dt>
|
||||||
|
<dd className="text-gray-900">{formatDateTime(asset.created_at)}</dd>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<dt className="text-xs text-gray-500">Last Updated</dt>
|
||||||
|
<dd className="text-gray-900">{formatDateTime(asset.updated_at)}</dd>
|
||||||
|
</div>
|
||||||
|
</dl>
|
||||||
|
<div>
|
||||||
|
<div className="text-xs text-gray-500">Remarks</div>
|
||||||
|
<div className="text-sm text-gray-800 mt-0.5 whitespace-pre-wrap">
|
||||||
|
{asset.remarks || "No remarks."}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{activeTab === "warranty" && (
|
||||||
|
<SimpleTable
|
||||||
|
emptyText="No warranty records for this asset."
|
||||||
|
headers={["Start Date", "End Date", "Duration", "Provider", "Status", "Remarks"]}
|
||||||
|
rows={warranties.map((w) => [
|
||||||
|
formatDate(w.start_date),
|
||||||
|
formatDate(w.end_date),
|
||||||
|
`${w.duration_months} months`,
|
||||||
|
w.provider_name || "—",
|
||||||
|
<CoverageBadge key="st" status={w.status} severity={w.severity} />,
|
||||||
|
w.remarks || "—",
|
||||||
|
])}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{activeTab === "contracts" && (
|
||||||
|
<SimpleTable
|
||||||
|
emptyText="No AMC/CMC contracts for this asset."
|
||||||
|
headers={["Type", "Provider", "Start Date", "End Date", "Coverage Period", "History / Status", "Remarks"]}
|
||||||
|
rows={contracts.map((c) => [
|
||||||
|
<Badge key="t" variant="info">{c.contract_type}</Badge>,
|
||||||
|
c.provider_name || `Provider #${c.provider_id}`,
|
||||||
|
formatDate(c.start_date),
|
||||||
|
formatDate(c.end_date),
|
||||||
|
c.coverage_period_text || "—",
|
||||||
|
c.is_superseded ? (
|
||||||
|
<Badge key="s" variant="outline">Superseded</Badge>
|
||||||
|
) : (
|
||||||
|
<CoverageBadge key="s" status={c.status} severity={c.severity} />
|
||||||
|
),
|
||||||
|
c.remarks || "—",
|
||||||
|
])}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{activeTab === "insurance" && (
|
||||||
|
<SimpleTable
|
||||||
|
emptyText="No insurance policies for this asset."
|
||||||
|
headers={["Policy No", "Insurer", "Start Date", "End Date", "Coverage Amount", "Status", "Remarks"]}
|
||||||
|
rows={insurance_policies.map((p) => [
|
||||||
|
<span key="pn" className="font-mono">{p.policy_no}</span>,
|
||||||
|
p.insurer_name || `Insurer #${p.insurer_id}`,
|
||||||
|
formatDate(p.start_date),
|
||||||
|
formatDate(p.end_date),
|
||||||
|
formatINR(p.coverage_amount),
|
||||||
|
<CoverageBadge key="st" status={p.status} severity={p.severity} />,
|
||||||
|
p.remarks || "—",
|
||||||
|
])}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{activeTab === "calibration" && (
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div className="bg-white rounded-lg border border-gray-200 p-4">
|
||||||
|
<h3 className="text-sm font-semibold text-gray-800 mb-2">Calibration Plan</h3>
|
||||||
|
{calibration_plan ? (
|
||||||
|
<div className="grid grid-cols-2 sm:grid-cols-4 gap-3 text-sm">
|
||||||
|
<div>
|
||||||
|
<div className="text-xs text-gray-500">Frequency</div>
|
||||||
|
<div className="font-medium">
|
||||||
|
{calibration_plan.frequency_months} months ({calibration_plan.calibrations_per_year}/yr)
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<div className="text-xs text-gray-500">Agency</div>
|
||||||
|
<div className="font-medium">{calibration_plan.agency_name || "—"}</div>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<div className="text-xs text-gray-500">Approved On</div>
|
||||||
|
<div className="font-medium">{formatDate(calibration_plan.approved_on)}</div>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<div className="text-xs text-gray-500">Next Due</div>
|
||||||
|
<div className="font-medium">{formatDate(calibration_plan.next_due_date)}</div>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
) : (
|
||||||
|
<p className="text-sm text-gray-400">No calibration plan configured.</p>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<SimpleTable
|
||||||
|
emptyText="No calibration records yet."
|
||||||
|
headers={["Due Date", "Completed Date", "Agency", "Certificate No", "Status", "Remarks"]}
|
||||||
|
rows={calibration_records.map((r) => [
|
||||||
|
formatDate(r.due_date),
|
||||||
|
formatDate(r.completed_date),
|
||||||
|
r.agency_name || "—",
|
||||||
|
r.certificate_no || "—",
|
||||||
|
<CalibrationBadge key="st" status={r.status} severity={r.severity} />,
|
||||||
|
r.remarks || "—",
|
||||||
|
])}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{activeTab === "pm" && (
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div>
|
||||||
|
<h3 className="text-sm font-semibold text-gray-800 mb-2">PM Schedules</h3>
|
||||||
|
<SimpleTable
|
||||||
|
emptyText="No PM schedules configured."
|
||||||
|
headers={["Frequency", "Service Mode", "Responsible / Provider", "Next Planned", "Active"]}
|
||||||
|
rows={pm_schedules.map((s) => [
|
||||||
|
`${s.frequency_months} months`,
|
||||||
|
s.service_mode,
|
||||||
|
s.provider_name || s.responsible_team || "—",
|
||||||
|
formatDate(s.next_planned_date),
|
||||||
|
<Badge key="a" variant={s.is_active ? "success" : "outline"}>
|
||||||
|
{s.is_active ? "Active" : "Inactive"}
|
||||||
|
</Badge>,
|
||||||
|
])}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
<div>
|
||||||
|
<h3 className="text-sm font-semibold text-gray-800 mb-2">Recent PM Records</h3>
|
||||||
|
<SimpleTable
|
||||||
|
emptyText="No PM records yet."
|
||||||
|
headers={["Planned Date", "Completed Date", "Status", "Service Details", "Remarks"]}
|
||||||
|
rows={pm_records.map((r) => [
|
||||||
|
formatDate(r.planned_date),
|
||||||
|
formatDate(r.completed_date),
|
||||||
|
<Badge key="st" variant={r.status === "completed" ? "success" : "warning"}>
|
||||||
|
{r.status}
|
||||||
|
</Badge>,
|
||||||
|
r.service_details || "—",
|
||||||
|
r.remarks || "—",
|
||||||
|
])}
|
||||||
|
/>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{activeTab === "breakdowns" && (
|
||||||
|
<SimpleTable
|
||||||
|
emptyText="No breakdown complaints recorded for this asset."
|
||||||
|
headers={["Complaint No", "Registered At", "Call Status", "Priority", "Closed At", "Description"]}
|
||||||
|
rows={complaints.map((c) => [
|
||||||
|
<Link
|
||||||
|
key="t"
|
||||||
|
to={`/complaints/${c.id}`}
|
||||||
|
className="font-mono text-[#1e3a8a] hover:underline font-medium"
|
||||||
|
>
|
||||||
|
{c.complaint_no}
|
||||||
|
</Link>,
|
||||||
|
formatDateTime(c.registered_at),
|
||||||
|
<Badge
|
||||||
|
key="st"
|
||||||
|
variant={
|
||||||
|
c.call_status === "closed"
|
||||||
|
? "success"
|
||||||
|
: c.call_status === "in_progress" || c.call_status === "assigned"
|
||||||
|
? "warning"
|
||||||
|
: "danger"
|
||||||
|
}
|
||||||
|
>
|
||||||
|
{c.call_status}
|
||||||
|
</Badge>,
|
||||||
|
c.priority,
|
||||||
|
formatDateTime(c.closed_at),
|
||||||
|
c.description,
|
||||||
|
])}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{activeTab === "documents" && (
|
||||||
|
<Attachments
|
||||||
|
entityType="asset"
|
||||||
|
entityId={asset.id}
|
||||||
|
canUpload={canFullEdit}
|
||||||
|
canDelete={canFullEdit}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
|
||||||
|
{canEdit && (
|
||||||
|
<AssetFormModal
|
||||||
|
open={editOpen}
|
||||||
|
onClose={() => setEditOpen(false)}
|
||||||
|
editing={asset}
|
||||||
|
coordinatorOnly={canContractOnlyEdit}
|
||||||
|
/>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
function SimpleTable({
|
||||||
|
headers,
|
||||||
|
rows,
|
||||||
|
emptyText,
|
||||||
|
}: {
|
||||||
|
headers: string[];
|
||||||
|
rows: React.ReactNode[][];
|
||||||
|
emptyText: string;
|
||||||
|
}) {
|
||||||
|
if (rows.length === 0) {
|
||||||
|
return (
|
||||||
|
<div className="bg-white border border-gray-200 rounded-lg p-8 text-center text-sm text-gray-400">
|
||||||
|
{emptyText}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
return (
|
||||||
|
<div className="bg-white border border-gray-200 rounded-lg overflow-hidden">
|
||||||
|
<div className="overflow-x-auto">
|
||||||
|
<table className="w-full text-sm">
|
||||||
|
<thead className="bg-gray-50 border-b border-gray-200">
|
||||||
|
<tr>
|
||||||
|
{headers.map((h) => (
|
||||||
|
<th key={h} className="text-left font-medium text-gray-600 px-4 py-3">
|
||||||
|
{h}
|
||||||
|
</th>
|
||||||
|
))}
|
||||||
|
</tr>
|
||||||
|
</thead>
|
||||||
|
<tbody className="divide-y divide-gray-100">
|
||||||
|
{rows.map((cells, idx) => (
|
||||||
|
<tr key={idx} className="hover:bg-gray-50/50">
|
||||||
|
{cells.map((cell, cIdx) => (
|
||||||
|
<td key={cIdx} className="px-4 py-3 text-gray-700">
|
||||||
|
{cell}
|
||||||
|
</td>
|
||||||
|
))}
|
||||||
|
</tr>
|
||||||
|
))}
|
||||||
|
</tbody>
|
||||||
|
</table>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -0,0 +1,220 @@
|
|||||||
|
import { useState } from "react";
|
||||||
|
import { useNavigate } from "react-router-dom";
|
||||||
|
import { useQuery } from "@tanstack/react-query";
|
||||||
|
import type { ColumnDef } from "@tanstack/react-table";
|
||||||
|
import { Plus } from "lucide-react";
|
||||||
|
import { assetsApi, type AssetItem, type AssetStatus } from "@/api/assets";
|
||||||
|
import { departmentsApi } from "@/api/masters";
|
||||||
|
import { useAuthStore } from "@/hooks/useAuth";
|
||||||
|
import { can } from "@/lib/permissions";
|
||||||
|
import { DataTable } from "@/components/DataTable";
|
||||||
|
import { Button } from "@/components/ui/button";
|
||||||
|
import {
|
||||||
|
AssetStatusBadge,
|
||||||
|
CoverageBadge,
|
||||||
|
CalibrationBadge,
|
||||||
|
} from "@/components/StatusBadge";
|
||||||
|
import { AssetFormModal } from "@/components/AssetFormModal";
|
||||||
|
|
||||||
|
const STATUS_CHIPS: { value: AssetStatus | ""; label: string }[] = [
|
||||||
|
{ value: "", label: "All Statuses" },
|
||||||
|
{ value: "in_service", label: "In Service" },
|
||||||
|
{ value: "under_repair", label: "Under Repair" },
|
||||||
|
{ value: "out_of_service", label: "Out of Service" },
|
||||||
|
{ value: "condemned", label: "Condemned" },
|
||||||
|
];
|
||||||
|
|
||||||
|
export function AssetsPage() {
|
||||||
|
const navigate = useNavigate();
|
||||||
|
const user = useAuthStore((s) => s.user);
|
||||||
|
const role = user?.role;
|
||||||
|
const isDeptUser = role === "department_user";
|
||||||
|
const canCreate = can(role, "create_edit_assets");
|
||||||
|
|
||||||
|
const [selectedDeptId, setSelectedDeptId] = useState<number | undefined>(undefined);
|
||||||
|
const [selectedStatus, setSelectedStatus] = useState<AssetStatus | "">("");
|
||||||
|
const [createOpen, setCreateOpen] = useState(false);
|
||||||
|
|
||||||
|
const deptsQuery = useQuery({
|
||||||
|
queryKey: ["departments", "active-only"],
|
||||||
|
queryFn: () => departmentsApi.list(false),
|
||||||
|
enabled: !isDeptUser,
|
||||||
|
});
|
||||||
|
|
||||||
|
const assetsQuery = useQuery({
|
||||||
|
queryKey: ["assets", selectedDeptId ?? "all", selectedStatus || "all"],
|
||||||
|
queryFn: () =>
|
||||||
|
assetsApi.list({
|
||||||
|
department_id: isDeptUser ? undefined : selectedDeptId,
|
||||||
|
status: selectedStatus || undefined,
|
||||||
|
page_size: 200,
|
||||||
|
}),
|
||||||
|
});
|
||||||
|
|
||||||
|
const columns: ColumnDef<AssetItem, unknown>[] = [
|
||||||
|
{
|
||||||
|
accessorKey: "asset_code",
|
||||||
|
header: "Asset Code",
|
||||||
|
enableColumnFilter: true,
|
||||||
|
cell: ({ getValue }) => (
|
||||||
|
<span className="font-mono font-semibold text-[#1e3a8a] whitespace-nowrap">
|
||||||
|
{String(getValue())}
|
||||||
|
</span>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{ accessorKey: "name", header: "Equipment Name", enableColumnFilter: true },
|
||||||
|
{
|
||||||
|
accessorKey: "category_name",
|
||||||
|
header: "Category",
|
||||||
|
enableColumnFilter: true,
|
||||||
|
cell: ({ getValue }) => (getValue() as string | null) || "—",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: "department_name",
|
||||||
|
header: "Department",
|
||||||
|
enableColumnFilter: true,
|
||||||
|
cell: ({ getValue }) => (getValue() as string | null) || "—",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: "location_name",
|
||||||
|
header: "Location",
|
||||||
|
enableColumnFilter: true,
|
||||||
|
cell: ({ getValue }) => (getValue() as string | null) || "—",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: "supplier_name",
|
||||||
|
header: "Supplier",
|
||||||
|
enableColumnFilter: true,
|
||||||
|
cell: ({ getValue }) => (getValue() as string | null) || "—",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: "status",
|
||||||
|
header: "Status",
|
||||||
|
enableColumnFilter: true,
|
||||||
|
cell: ({ getValue }) => <AssetStatusBadge status={String(getValue())} />,
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: "warranty_status",
|
||||||
|
header: "Warranty",
|
||||||
|
enableColumnFilter: true,
|
||||||
|
cell: ({ row }) => (
|
||||||
|
<CoverageBadge
|
||||||
|
status={row.original.warranty_status}
|
||||||
|
severity={row.original.warranty_severity}
|
||||||
|
/>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: "contract_status",
|
||||||
|
header: "Contract",
|
||||||
|
enableColumnFilter: true,
|
||||||
|
cell: ({ row }) => (
|
||||||
|
<CoverageBadge
|
||||||
|
status={row.original.contract_status}
|
||||||
|
severity={row.original.contract_severity}
|
||||||
|
prefix={row.original.contract_type ?? undefined}
|
||||||
|
/>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
{
|
||||||
|
accessorKey: "calibration_status",
|
||||||
|
header: "Calibration",
|
||||||
|
enableColumnFilter: true,
|
||||||
|
cell: ({ row }) => (
|
||||||
|
<CalibrationBadge
|
||||||
|
status={row.original.calibration_status}
|
||||||
|
severity={row.original.calibration_severity}
|
||||||
|
/>
|
||||||
|
),
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
const departments = deptsQuery.data?.items ?? [];
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="space-y-4">
|
||||||
|
<div className="flex flex-wrap items-center justify-between gap-3">
|
||||||
|
<div>
|
||||||
|
<h1 className="text-2xl font-bold text-gray-900">Asset Register</h1>
|
||||||
|
<p className="text-sm text-gray-500 mt-0.5">
|
||||||
|
{isDeptUser && user?.department_name
|
||||||
|
? `Showing assets in ${user.department_name}`
|
||||||
|
: "Hospital biomedical and facility equipment inventory"}
|
||||||
|
</p>
|
||||||
|
</div>
|
||||||
|
{canCreate && (
|
||||||
|
<Button onClick={() => setCreateOpen(true)}>
|
||||||
|
<Plus className="h-4 w-4 mr-1.5" />
|
||||||
|
Add Asset
|
||||||
|
</Button>
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
|
||||||
|
{/* Quick Filter Chips */}
|
||||||
|
<div className="space-y-2">
|
||||||
|
{!isDeptUser && departments.length > 0 && (
|
||||||
|
<div className="flex items-center gap-1.5 flex-wrap">
|
||||||
|
<span className="text-xs font-medium text-gray-500 mr-1">Department:</span>
|
||||||
|
<button
|
||||||
|
type="button"
|
||||||
|
onClick={() => setSelectedDeptId(undefined)}
|
||||||
|
className={`px-2.5 py-1 rounded-full text-xs font-medium transition-colors ${
|
||||||
|
selectedDeptId === undefined
|
||||||
|
? "bg-[#1e3a8a] text-white"
|
||||||
|
: "bg-white border border-gray-200 text-gray-700 hover:bg-gray-50"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
All Departments
|
||||||
|
</button>
|
||||||
|
{departments.map((d) => (
|
||||||
|
<button
|
||||||
|
key={d.id}
|
||||||
|
type="button"
|
||||||
|
onClick={() => setSelectedDeptId(d.id)}
|
||||||
|
className={`px-2.5 py-1 rounded-full text-xs font-medium transition-colors ${
|
||||||
|
selectedDeptId === d.id
|
||||||
|
? "bg-[#1e3a8a] text-white"
|
||||||
|
: "bg-white border border-gray-200 text-gray-700 hover:bg-gray-50"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{d.code}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
)}
|
||||||
|
|
||||||
|
<div className="flex items-center gap-1.5 flex-wrap">
|
||||||
|
<span className="text-xs font-medium text-gray-500 mr-1">Status:</span>
|
||||||
|
{STATUS_CHIPS.map((chip) => (
|
||||||
|
<button
|
||||||
|
key={chip.value || "all"}
|
||||||
|
type="button"
|
||||||
|
onClick={() => setSelectedStatus(chip.value)}
|
||||||
|
className={`px-2.5 py-1 rounded-full text-xs font-medium transition-colors ${
|
||||||
|
selectedStatus === chip.value
|
||||||
|
? "bg-blue-700 text-white"
|
||||||
|
: "bg-white border border-gray-200 text-gray-700 hover:bg-gray-50"
|
||||||
|
}`}
|
||||||
|
>
|
||||||
|
{chip.label}
|
||||||
|
</button>
|
||||||
|
))}
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<DataTable
|
||||||
|
data={assetsQuery.data?.items ?? []}
|
||||||
|
columns={columns}
|
||||||
|
loading={assetsQuery.isLoading}
|
||||||
|
globalFilterPlaceholder="Search by asset code, equipment, department, serial..."
|
||||||
|
exportFilename="poona-hospital-assets"
|
||||||
|
emptyMessage="No assets match the current filters."
|
||||||
|
onRowClick={(row) => navigate(`/assets/${row.id}`)}
|
||||||
|
/>
|
||||||
|
|
||||||
|
{canCreate && (
|
||||||
|
<AssetFormModal open={createOpen} onClose={() => setCreateOpen(false)} />
|
||||||
|
)}
|
||||||
|
</div>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -36,9 +36,6 @@ export const DashboardPage = () => (
|
|||||||
</div>
|
</div>
|
||||||
</StubPage>
|
</StubPage>
|
||||||
);
|
);
|
||||||
export const AssetsPage = () => (
|
|
||||||
<StubPage title="Asset Register" phase={2} description="60+ assets with column filters and detail tabs." />
|
|
||||||
);
|
|
||||||
export const ComplaintsPage = () => (
|
export const ComplaintsPage = () => (
|
||||||
<StubPage
|
<StubPage
|
||||||
title="Breakdown & Complaint Register"
|
title="Breakdown & Complaint Register"
|
||||||
|
|||||||
@@ -0,0 +1,110 @@
|
|||||||
|
import { useState } from "react";
|
||||||
|
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||||
|
import { render, screen, fireEvent, waitFor } from "@testing-library/react";
|
||||||
|
import { AssetPicker } from "@/components/AssetPicker";
|
||||||
|
import { assetsApi, type AssetLookupItem } from "@/api/assets";
|
||||||
|
|
||||||
|
const MOCK_ITEMS: AssetLookupItem[] = [
|
||||||
|
{
|
||||||
|
id: 1,
|
||||||
|
asset_code: "PHRC-ICU-0001",
|
||||||
|
serial_no: "SN-VENT-101",
|
||||||
|
name: "ICU Ventilator",
|
||||||
|
category_id: 1,
|
||||||
|
category_name: "Life Support",
|
||||||
|
department_id: 1,
|
||||||
|
department_name: "ICU",
|
||||||
|
location_id: 1,
|
||||||
|
location_name: "ICU Bay 1",
|
||||||
|
supplier_id: 1,
|
||||||
|
supplier_name: "MedTech India",
|
||||||
|
status: "in_service",
|
||||||
|
criticality: "critical",
|
||||||
|
requires_calibration: true,
|
||||||
|
insurance_applicable: true,
|
||||||
|
warranty_status: "active",
|
||||||
|
warranty_end_date: "2027-05-01",
|
||||||
|
contract_status: "active",
|
||||||
|
contract_type: "CMC",
|
||||||
|
contract_end_date: "2027-12-31",
|
||||||
|
contract_summary: "CMC — Active until 31-Dec-2027",
|
||||||
|
insurance_status: "active",
|
||||||
|
insurance_end_date: "2027-06-30",
|
||||||
|
insurance_summary: "Policy #INS-100 (Active)",
|
||||||
|
},
|
||||||
|
{
|
||||||
|
id: 2,
|
||||||
|
asset_code: "PHRC-RAD-0009",
|
||||||
|
serial_no: "SN-XR-99",
|
||||||
|
name: "Portable X-Ray",
|
||||||
|
category_id: 2,
|
||||||
|
category_name: "Imaging",
|
||||||
|
department_id: 2,
|
||||||
|
department_name: "Radiology",
|
||||||
|
location_id: 2,
|
||||||
|
location_name: "X-Ray Room",
|
||||||
|
supplier_id: null,
|
||||||
|
supplier_name: null,
|
||||||
|
status: "condemned",
|
||||||
|
criticality: "non_critical",
|
||||||
|
requires_calibration: false,
|
||||||
|
insurance_applicable: false,
|
||||||
|
warranty_status: "none",
|
||||||
|
warranty_end_date: null,
|
||||||
|
contract_status: "none",
|
||||||
|
contract_type: null,
|
||||||
|
contract_end_date: null,
|
||||||
|
contract_summary: "No active contract",
|
||||||
|
insurance_status: "none",
|
||||||
|
insurance_end_date: null,
|
||||||
|
insurance_summary: "No policy",
|
||||||
|
},
|
||||||
|
];
|
||||||
|
|
||||||
|
function PickerHarness({ onPicked }: { onPicked?: (a: AssetLookupItem | null) => void }) {
|
||||||
|
const [selected, setSelected] = useState<AssetLookupItem | null>(null);
|
||||||
|
return (
|
||||||
|
<AssetPicker
|
||||||
|
selectedAsset={selected}
|
||||||
|
onSelect={(item) => {
|
||||||
|
setSelected(item);
|
||||||
|
onPicked?.(item);
|
||||||
|
}}
|
||||||
|
/>
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("AssetPicker", () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.restoreAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("renders search results with badges and pre-fills summary card on selection", async () => {
|
||||||
|
const lookupSpy = vi
|
||||||
|
.spyOn(assetsApi, "lookup")
|
||||||
|
.mockResolvedValue({ items: MOCK_ITEMS });
|
||||||
|
const onPicked = vi.fn();
|
||||||
|
|
||||||
|
render(<PickerHarness onPicked={onPicked} />);
|
||||||
|
|
||||||
|
const input = screen.getByPlaceholderText(/Search by asset code/i);
|
||||||
|
fireEvent.focus(input);
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(lookupSpy).toHaveBeenCalled();
|
||||||
|
expect(screen.getByText(/ICU Ventilator/)).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
expect(screen.getByText("Under Warranty")).toBeInTheDocument();
|
||||||
|
expect(screen.getByText("Condemned")).toBeInTheDocument();
|
||||||
|
|
||||||
|
fireEvent.click(screen.getByText(/ICU Ventilator/));
|
||||||
|
|
||||||
|
expect(onPicked).toHaveBeenCalledWith(MOCK_ITEMS[0]);
|
||||||
|
expect(screen.getByText("Life Support")).toBeInTheDocument();
|
||||||
|
expect(screen.getByText("ICU Bay 1")).toBeInTheDocument();
|
||||||
|
expect(screen.getByText("CMC — Active until 31-Dec-2027")).toBeInTheDocument();
|
||||||
|
expect(screen.getByText("Policy #INS-100 (Active)")).toBeInTheDocument();
|
||||||
|
expect(screen.getByText("Under Warranty")).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,72 @@
|
|||||||
|
import { describe, it, expect, vi, beforeEach } from "vitest";
|
||||||
|
import { render, screen, fireEvent, waitFor } from "@testing-library/react";
|
||||||
|
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
|
||||||
|
import { Attachments, validateAttachmentFile } from "@/components/Attachments";
|
||||||
|
import { attachmentsApi } from "@/api/attachments";
|
||||||
|
|
||||||
|
function renderWithQuery(ui: React.ReactNode) {
|
||||||
|
const qc = new QueryClient({
|
||||||
|
defaultOptions: { queries: { retry: false } },
|
||||||
|
});
|
||||||
|
return render(<QueryClientProvider client={qc}>{ui}</QueryClientProvider>);
|
||||||
|
}
|
||||||
|
|
||||||
|
describe("Attachments", () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
vi.restoreAllMocks();
|
||||||
|
});
|
||||||
|
|
||||||
|
it("validates allowed file types and 10 MB size limit", () => {
|
||||||
|
const validPdf = new File(["%PDF-1.4"], "manual.pdf", { type: "application/pdf" });
|
||||||
|
const validJpg = new File(["abc"], "photo.jpg", { type: "image/jpeg" });
|
||||||
|
const badExe = new File(["MZ"], "malware.exe", { type: "application/octet-stream" });
|
||||||
|
const bigFile = new File(["x"], "huge.pdf", { type: "application/pdf" });
|
||||||
|
Object.defineProperty(bigFile, "size", { value: 11 * 1024 * 1024 });
|
||||||
|
|
||||||
|
expect(validateAttachmentFile(validPdf)).toBeNull();
|
||||||
|
expect(validateAttachmentFile(validJpg)).toBeNull();
|
||||||
|
expect(validateAttachmentFile(badExe)).toMatch(/Invalid file type/i);
|
||||||
|
expect(validateAttachmentFile(bigFile)).toMatch(/too large/i);
|
||||||
|
});
|
||||||
|
|
||||||
|
it("renders list and blocks invalid or oversized uploads with clear error banner", async () => {
|
||||||
|
vi.spyOn(attachmentsApi, "list").mockResolvedValue({
|
||||||
|
items: [
|
||||||
|
{
|
||||||
|
id: 10,
|
||||||
|
entity_type: "asset",
|
||||||
|
entity_id: 1,
|
||||||
|
original_name: "invoice.pdf",
|
||||||
|
mime_type: "application/pdf",
|
||||||
|
size_bytes: 2048,
|
||||||
|
uploaded_by_name: "Admin",
|
||||||
|
uploaded_at: "2026-11-10T09:30:00Z",
|
||||||
|
},
|
||||||
|
],
|
||||||
|
total: 1,
|
||||||
|
});
|
||||||
|
const uploadSpy = vi.spyOn(attachmentsApi, "upload");
|
||||||
|
|
||||||
|
renderWithQuery(
|
||||||
|
<Attachments entityType="asset" entityId={1} canUpload={true} canDelete={true} />
|
||||||
|
);
|
||||||
|
|
||||||
|
await waitFor(() => {
|
||||||
|
expect(screen.getByText("invoice.pdf")).toBeInTheDocument();
|
||||||
|
});
|
||||||
|
|
||||||
|
const input = screen.getByLabelText("Upload attachment") as HTMLInputElement;
|
||||||
|
const badTxt = new File(["hello"], "notes.txt", { type: "text/plain" });
|
||||||
|
fireEvent.change(input, { target: { files: [badTxt] } });
|
||||||
|
|
||||||
|
expect(screen.getByRole("alert")).toHaveTextContent(/Invalid file type/i);
|
||||||
|
expect(uploadSpy).not.toHaveBeenCalled();
|
||||||
|
|
||||||
|
const oversized = new File(["x"], "big.png", { type: "image/png" });
|
||||||
|
Object.defineProperty(oversized, "size", { value: 12 * 1024 * 1024 });
|
||||||
|
fireEvent.change(input, { target: { files: [oversized] } });
|
||||||
|
|
||||||
|
expect(screen.getByRole("alert")).toHaveTextContent(/too large/i);
|
||||||
|
expect(uploadSpy).not.toHaveBeenCalled();
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -1 +1 @@
|
|||||||
{"root":["./src/app.tsx","./src/main.tsx","./src/vite-env.d.ts","./src/api/auth.ts","./src/api/client.ts","./src/api/health.ts","./src/api/masters.ts","./src/api/settings.ts","./src/components/datatable/datatable.test.tsx","./src/components/datatable/datatable.tsx","./src/components/datatable/index.ts","./src/components/layout/appshell.tsx","./src/components/layout/sidebar.tsx","./src/components/layout/topbar.tsx","./src/components/ui/badge.tsx","./src/components/ui/button.tsx","./src/components/ui/dialog.tsx","./src/hooks/useauth.ts","./src/lib/format.ts","./src/lib/permissions.ts","./src/lib/utils.ts","./src/pages/accessdeniedpage.tsx","./src/pages/datatabledemopage.tsx","./src/pages/loginpage.tsx","./src/pages/masterspage.tsx","./src/pages/settingspage.tsx","./src/pages/stubs.tsx","./src/test/login.test.tsx","./src/test/permissions.test.ts","./src/test/setup.ts","./src/test/smoke.test.tsx"],"version":"5.6.3"}
|
{"root":["./src/app.tsx","./src/main.tsx","./src/vite-env.d.ts","./src/api/assets.ts","./src/api/attachments.ts","./src/api/auth.ts","./src/api/client.ts","./src/api/health.ts","./src/api/masters.ts","./src/api/settings.ts","./src/components/assetformmodal.tsx","./src/components/assetpicker.tsx","./src/components/attachments.tsx","./src/components/statusbadge.tsx","./src/components/datatable/datatable.test.tsx","./src/components/datatable/datatable.tsx","./src/components/datatable/index.ts","./src/components/layout/appshell.tsx","./src/components/layout/sidebar.tsx","./src/components/layout/topbar.tsx","./src/components/ui/badge.tsx","./src/components/ui/button.tsx","./src/components/ui/dialog.tsx","./src/hooks/useauth.ts","./src/lib/format.ts","./src/lib/permissions.ts","./src/lib/utils.ts","./src/pages/accessdeniedpage.tsx","./src/pages/assetdetailpage.tsx","./src/pages/assetspage.tsx","./src/pages/datatabledemopage.tsx","./src/pages/loginpage.tsx","./src/pages/masterspage.tsx","./src/pages/settingspage.tsx","./src/pages/stubs.tsx","./src/test/asset-picker.test.tsx","./src/test/attachments.test.tsx","./src/test/login.test.tsx","./src/test/permissions.test.ts","./src/test/setup.ts","./src/test/smoke.test.tsx"],"version":"5.6.3"}
|
||||||
Reference in New Issue
Block a user