phase-2: asset register, detail overview, asset picker, attachments
This commit is contained in:
@@ -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.responses import JSONResponse
|
||||
from .core.db import SessionLocal, engine
|
||||
from .core.exceptions import CodedHTTPException, coded_http_exception_handler
|
||||
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
|
||||
|
||||
logging.basicConfig(
|
||||
@@ -42,6 +43,8 @@ app.add_middleware(
|
||||
allow_headers=["*"],
|
||||
)
|
||||
|
||||
app.add_exception_handler(CodedHTTPException, coded_http_exception_handler)
|
||||
|
||||
|
||||
@app.exception_handler(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(masters.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 .masters import (
|
||||
CategoryCreate,
|
||||
@@ -21,6 +31,15 @@ from .masters import (
|
||||
from .settings import DemoDateIn, DemoDateOut, SettingItemOut, SettingsListOut, SettingsUpdateIn
|
||||
|
||||
__all__ = [
|
||||
"AssetCreate",
|
||||
"AssetListOut",
|
||||
"AssetLookupListOut",
|
||||
"AssetLookupOut",
|
||||
"AssetOut",
|
||||
"AssetOverviewOut",
|
||||
"AssetUpdate",
|
||||
"AttachmentListOut",
|
||||
"AttachmentOut",
|
||||
"LoginRequest",
|
||||
"TokenResponse",
|
||||
"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")
|
||||
Reference in New Issue
Block a user