initial commit
This commit is contained in:
@@ -0,0 +1,45 @@
|
||||
from . import (
|
||||
assets,
|
||||
attachments,
|
||||
audit,
|
||||
auth,
|
||||
calibration,
|
||||
complaints,
|
||||
contracts,
|
||||
dashboard,
|
||||
demo_equipment,
|
||||
health,
|
||||
insurance,
|
||||
masters,
|
||||
notifications,
|
||||
pm,
|
||||
reports,
|
||||
search,
|
||||
settings,
|
||||
users,
|
||||
visits,
|
||||
warranties,
|
||||
)
|
||||
|
||||
__all__ = [
|
||||
"assets",
|
||||
"attachments",
|
||||
"audit",
|
||||
"auth",
|
||||
"calibration",
|
||||
"complaints",
|
||||
"contracts",
|
||||
"dashboard",
|
||||
"demo_equipment",
|
||||
"health",
|
||||
"insurance",
|
||||
"masters",
|
||||
"notifications",
|
||||
"pm",
|
||||
"reports",
|
||||
"search",
|
||||
"settings",
|
||||
"users",
|
||||
"visits",
|
||||
"warranties",
|
||||
]
|
||||
@@ -0,0 +1,599 @@
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
from typing import Any, Literal, Optional
|
||||
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query
|
||||
from fastapi.responses import StreamingResponse
|
||||
from pydantic import BaseModel, Field
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..core.db import get_db
|
||||
from ..core.deps import require_roles
|
||||
from ..models import User
|
||||
from ..services.ai_metrics import (
|
||||
compute_breakdown_frequency_from_dataset,
|
||||
compute_comparison_from_dataset,
|
||||
compute_depreciation_from_dataset,
|
||||
compute_efficiency_from_dataset,
|
||||
format_inr,
|
||||
load_ai_dataset,
|
||||
make_metric,
|
||||
resolve_period,
|
||||
)
|
||||
from ..services.ai_narrative import get_or_generate_narrative
|
||||
from ..services.ai_provider import get_ai_status
|
||||
from ..services.ai_suggestions import generate_suggestions
|
||||
from ..services.exports import build_ai_xlsx, build_csv
|
||||
from ..services.permissions import Role
|
||||
|
||||
router = APIRouter(prefix="/ai", tags=["ai"])
|
||||
|
||||
AI_VIEW_ROLES = (
|
||||
Role.system_admin,
|
||||
Role.biomedical,
|
||||
Role.management,
|
||||
Role.coordinator,
|
||||
)
|
||||
|
||||
SECTION_ALIASES: dict[str, str] = {
|
||||
"summary": "summary",
|
||||
"comparison": "comparison",
|
||||
"depreciation": "depreciation",
|
||||
"efficiency": "efficiency",
|
||||
"breakdown-frequency": "breakdown_frequency",
|
||||
"breakdown_frequency": "breakdown_frequency",
|
||||
}
|
||||
|
||||
|
||||
class RegenerateNarrativeRequest(BaseModel):
|
||||
section: str
|
||||
filters: dict[str, Any] = Field(default_factory=dict)
|
||||
|
||||
|
||||
def _ai_query_params(
|
||||
period: Literal["3m", "6m", "12m", "custom"] = Query("12m"),
|
||||
date_from: Optional[date] = Query(None),
|
||||
date_to: Optional[date] = Query(None),
|
||||
department_id: Optional[int] = Query(None),
|
||||
category_id: Optional[int] = Query(None),
|
||||
) -> dict[str, Any]:
|
||||
if period == "custom" and date_from and date_to and date_from > date_to:
|
||||
raise HTTPException(status_code=422, detail="date_from must be on or before date_to.")
|
||||
return {
|
||||
"period": period,
|
||||
"date_from": date_from,
|
||||
"date_to": date_to,
|
||||
"department_id": department_id,
|
||||
"category_id": category_id,
|
||||
}
|
||||
|
||||
|
||||
def _parse_optional_date(val: Any) -> Optional[date]:
|
||||
if val is None or val == "":
|
||||
return None
|
||||
if isinstance(val, date):
|
||||
return val
|
||||
try:
|
||||
return date.fromisoformat(str(val)[:10])
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=422, detail=f"Invalid date value: {val}")
|
||||
|
||||
|
||||
def _filters_echo(dataset: dict[str, Any], params: dict[str, Any]) -> dict[str, Any]:
|
||||
echo: dict[str, Any] = {
|
||||
"period": params.get("period", "12m"),
|
||||
"period_start": str(dataset["period_start"]),
|
||||
"period_end": str(dataset["period_end"]),
|
||||
}
|
||||
if params.get("department_id") is not None:
|
||||
echo["department_id"] = int(params["department_id"])
|
||||
if params.get("category_id") is not None:
|
||||
echo["category_id"] = int(params["category_id"])
|
||||
return echo
|
||||
|
||||
|
||||
def _load_scoped_dataset(db: Session, user: User, params: dict[str, Any]) -> dict[str, Any]:
|
||||
period = str(params.get("period") or "12m")
|
||||
if period not in ("3m", "6m", "12m", "custom"):
|
||||
raise HTTPException(status_code=422, detail="period must be one of 3m, 6m, 12m, custom.")
|
||||
d_from = _parse_optional_date(params.get("date_from"))
|
||||
d_to = _parse_optional_date(params.get("date_to"))
|
||||
if period == "custom" and d_from and d_to and d_from > d_to:
|
||||
raise HTTPException(status_code=422, detail="date_from must be on or before date_to.")
|
||||
dept_id = int(params["department_id"]) if params.get("department_id") not in (None, "") else None
|
||||
cat_id = int(params["category_id"]) if params.get("category_id") not in (None, "") else None
|
||||
|
||||
p_start, p_end = resolve_period(db, period=period, date_from=d_from, date_to=d_to)
|
||||
return load_ai_dataset(
|
||||
db,
|
||||
user,
|
||||
p_start,
|
||||
p_end,
|
||||
department_id=dept_id,
|
||||
category_id=cat_id,
|
||||
)
|
||||
|
||||
|
||||
def _build_section_bundle(
|
||||
db: Session,
|
||||
user: User,
|
||||
canonical_section: str,
|
||||
params: dict[str, Any],
|
||||
*,
|
||||
force_regenerate: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
dataset = _load_scoped_dataset(db, user, params)
|
||||
echo = _filters_echo(dataset, params)
|
||||
|
||||
if canonical_section == "comparison":
|
||||
data = compute_comparison_from_dataset(dataset)
|
||||
narrative = get_or_generate_narrative(
|
||||
db,
|
||||
"comparison",
|
||||
echo,
|
||||
data["metrics"],
|
||||
section_data=data,
|
||||
user_id=user.id,
|
||||
force_regenerate=force_regenerate,
|
||||
)
|
||||
return {
|
||||
**data,
|
||||
"period_start": str(dataset["period_start"]),
|
||||
"period_end": str(dataset["period_end"]),
|
||||
"filters_applied": echo,
|
||||
"narrative": narrative,
|
||||
}
|
||||
|
||||
if canonical_section == "depreciation":
|
||||
data = compute_depreciation_from_dataset(dataset)
|
||||
narrative = get_or_generate_narrative(
|
||||
db,
|
||||
"depreciation",
|
||||
echo,
|
||||
data["metrics"],
|
||||
section_data=data,
|
||||
user_id=user.id,
|
||||
force_regenerate=force_regenerate,
|
||||
)
|
||||
return {
|
||||
**data,
|
||||
"period_start": str(dataset["period_start"]),
|
||||
"period_end": str(dataset["period_end"]),
|
||||
"filters_applied": echo,
|
||||
"narrative": narrative,
|
||||
}
|
||||
|
||||
if canonical_section == "efficiency":
|
||||
data = compute_efficiency_from_dataset(dataset)
|
||||
narrative = get_or_generate_narrative(
|
||||
db,
|
||||
"efficiency",
|
||||
echo,
|
||||
data["metrics"],
|
||||
section_data=data,
|
||||
user_id=user.id,
|
||||
force_regenerate=force_regenerate,
|
||||
)
|
||||
return {
|
||||
**data,
|
||||
"period_start": str(dataset["period_start"]),
|
||||
"period_end": str(dataset["period_end"]),
|
||||
"filters_applied": echo,
|
||||
"narrative": narrative,
|
||||
}
|
||||
|
||||
if canonical_section == "breakdown_frequency":
|
||||
data = compute_breakdown_frequency_from_dataset(dataset)
|
||||
narrative = get_or_generate_narrative(
|
||||
db,
|
||||
"breakdown_frequency",
|
||||
echo,
|
||||
data["metrics"],
|
||||
section_data=data,
|
||||
user_id=user.id,
|
||||
force_regenerate=force_regenerate,
|
||||
)
|
||||
return {
|
||||
**data,
|
||||
"period_start": str(dataset["period_start"]),
|
||||
"period_end": str(dataset["period_end"]),
|
||||
"filters_applied": echo,
|
||||
"narrative": narrative,
|
||||
}
|
||||
|
||||
# Whole-report summary
|
||||
cmp_data = compute_comparison_from_dataset(dataset)
|
||||
dep_data = compute_depreciation_from_dataset(dataset)
|
||||
eff_data = compute_efficiency_from_dataset(dataset)
|
||||
bf_data = compute_breakdown_frequency_from_dataset(dataset)
|
||||
sug_data = generate_suggestions(
|
||||
dataset,
|
||||
comparison=cmp_data,
|
||||
depreciation_data=dep_data,
|
||||
efficiency_data=eff_data,
|
||||
breakdown_data=bf_data,
|
||||
)
|
||||
|
||||
# Collect headline metrics from all 4 sections + suggestion count
|
||||
headline_ids = {
|
||||
"m_cmp_horizon_years",
|
||||
"m_cmp_latest_count",
|
||||
"m_cmp_inhouse_wins",
|
||||
"m_cmp_outsourced_wins",
|
||||
"m_cmp_rent_wins",
|
||||
"m_dep_total_purchase_value",
|
||||
"m_dep_total_book_value",
|
||||
"m_dep_total_accumulated",
|
||||
"m_dep_total_maintenance",
|
||||
"m_dep_fully_depreciated_count",
|
||||
"m_dep_review_flag_count",
|
||||
"m_eff_avg_uptime",
|
||||
"m_eff_mttr",
|
||||
"m_eff_mtbf",
|
||||
"m_eff_pm_compliance",
|
||||
"m_eff_score_overall",
|
||||
"m_bf_total_breakdowns",
|
||||
"m_bf_assets_in_scope",
|
||||
"m_bf_avg_per_equipment",
|
||||
"m_bf_repeat_failure_assets",
|
||||
}
|
||||
summary_metrics: list[dict[str, Any]] = []
|
||||
seen: set[str] = set()
|
||||
for sec_obj in (cmp_data, dep_data, eff_data, bf_data):
|
||||
for m in sec_obj.get("metrics", []):
|
||||
if m["id"] in headline_ids and m["id"] not in seen:
|
||||
summary_metrics.append(m)
|
||||
seen.add(m["id"])
|
||||
summary_metrics.append(
|
||||
make_metric("m_sug_total_count", "Total Advisory Suggestions", len(sug_data["suggestions"]), "count")
|
||||
)
|
||||
|
||||
narrative = get_or_generate_narrative(
|
||||
db,
|
||||
"summary",
|
||||
echo,
|
||||
summary_metrics,
|
||||
suggestions=sug_data["suggestions"],
|
||||
user_id=user.id,
|
||||
force_regenerate=force_regenerate,
|
||||
)
|
||||
|
||||
how_calculated = {
|
||||
"formulas": (
|
||||
cmp_data["how_calculated"]["formulas"]
|
||||
+ dep_data["how_calculated"]["formulas"]
|
||||
+ eff_data["how_calculated"]["formulas"]
|
||||
+ bf_data["how_calculated"]["formulas"]
|
||||
),
|
||||
"weights": eff_data["how_calculated"].get("weights", {}),
|
||||
"settings_used": {
|
||||
**cmp_data["how_calculated"].get("settings_used", {}),
|
||||
**dep_data["how_calculated"].get("settings_used", {}),
|
||||
**eff_data["how_calculated"].get("settings_used", {}),
|
||||
**bf_data["how_calculated"].get("settings_used", {}),
|
||||
},
|
||||
}
|
||||
|
||||
return {
|
||||
"section": "summary",
|
||||
"title": "AI Report Executive Summary",
|
||||
"period_start": str(dataset["period_start"]),
|
||||
"period_end": str(dataset["period_end"]),
|
||||
"filters_applied": echo,
|
||||
"sections": {
|
||||
"comparison": cmp_data["summary"],
|
||||
"depreciation": dep_data["summary"],
|
||||
"efficiency": eff_data["summary"],
|
||||
"breakdown_frequency": bf_data["summary"],
|
||||
},
|
||||
"suggestions": sug_data["suggestions"],
|
||||
"suggestions_evidence": sug_data["evidence"],
|
||||
"metrics": summary_metrics,
|
||||
"narrative": narrative,
|
||||
"how_calculated": how_calculated,
|
||||
}
|
||||
|
||||
|
||||
def _build_export_payload(canonical_section: str, bundle: dict[str, Any]) -> dict[str, Any]:
|
||||
if canonical_section == "comparison":
|
||||
columns = [
|
||||
{"key": "asset_code", "label": "Asset Code"},
|
||||
{"key": "asset_name", "label": "Equipment Name"},
|
||||
{"key": "department_name", "label": "Department"},
|
||||
{"key": "category_name", "label": "Category"},
|
||||
{"key": "purchase_value", "label": "Purchase Price"},
|
||||
{"key": "in_house_display", "label": "In-House Cost"},
|
||||
{"key": "outsourced_display", "label": "Outsourced Cost"},
|
||||
{"key": "rent_display", "label": "Rent Cost"},
|
||||
{"key": "lowest_scenario_label", "label": "Lowest Option"},
|
||||
{"key": "savings_vs_next", "label": "Difference vs Next"},
|
||||
]
|
||||
rows = []
|
||||
for r in bundle["rows"]:
|
||||
rows.append(
|
||||
{
|
||||
"asset_code": r["asset_code"],
|
||||
"asset_name": r["asset_name"],
|
||||
"department_name": r["department_name"],
|
||||
"category_name": r["category_name"],
|
||||
"purchase_value": r["purchase_value"] if r["purchase_value"] is not None else "Insufficient data: purchase_value",
|
||||
"in_house_display": r["in_house_cost"] if r["in_house_cost"] is not None else (r["in_house_reason"] or "Insufficient data"),
|
||||
"outsourced_display": r["outsourced_cost"] if r["outsourced_cost"] is not None else (r["outsourced_reason"] or "Insufficient data"),
|
||||
"rent_display": r["rent_cost"] if r["rent_cost"] is not None else (r["rent_reason"] or "Insufficient data"),
|
||||
"lowest_scenario_label": r["lowest_scenario_label"] or "Insufficient data",
|
||||
"savings_vs_next": r["savings_vs_next"] if r["savings_vs_next"] is not None else "—",
|
||||
}
|
||||
)
|
||||
return {
|
||||
"title": bundle["title"],
|
||||
"filters_applied": bundle["filters_applied"],
|
||||
"summary": bundle["summary"],
|
||||
"columns": columns,
|
||||
"rows": rows,
|
||||
}
|
||||
|
||||
if canonical_section == "depreciation":
|
||||
columns = [
|
||||
{"key": "asset_code", "label": "Asset Code"},
|
||||
{"key": "asset_name", "label": "Equipment Name"},
|
||||
{"key": "department_name", "label": "Department"},
|
||||
{"key": "category_name", "label": "Category"},
|
||||
{"key": "acquisition_mode", "label": "Mode"},
|
||||
{"key": "purchase_value", "label": "Purchase Value"},
|
||||
{"key": "method", "label": "Method"},
|
||||
{"key": "book_value", "label": "Book Value"},
|
||||
{"key": "accumulated_depreciation", "label": "Accumulated Depreciation"},
|
||||
{"key": "maintenance_cost", "label": "Maintenance Cost"},
|
||||
{"key": "maintenance_ratio_pct", "label": "Maintenance Ratio %"},
|
||||
{"key": "lifetime_cost", "label": "Lifetime Cost"},
|
||||
{"key": "review_flag", "label": "Replacement Review"},
|
||||
]
|
||||
rows = []
|
||||
for r in bundle["rows"]:
|
||||
ratio_pct = round(r["maintenance_ratio"] * 100.0, 1) if r["maintenance_ratio"] is not None else None
|
||||
rows.append(
|
||||
{
|
||||
"asset_code": r["asset_code"],
|
||||
"asset_name": r["asset_name"],
|
||||
"department_name": r["department_name"],
|
||||
"category_name": r["category_name"],
|
||||
"acquisition_mode": r["acquisition_mode"],
|
||||
"purchase_value": r["purchase_value"] if r["purchase_value"] is not None else (r["depreciation_reason"] or "Insufficient data"),
|
||||
"method": r["method"] or (r["depreciation_reason"] or "N/A"),
|
||||
"book_value": r["book_value"] if r["book_value"] is not None else (r["depreciation_reason"] or "N/A"),
|
||||
"accumulated_depreciation": r["accumulated_depreciation"] if r["accumulated_depreciation"] is not None else "N/A",
|
||||
"maintenance_cost": r["maintenance_cost"],
|
||||
"maintenance_ratio_pct": ratio_pct if ratio_pct is not None else "N/A",
|
||||
"lifetime_cost": r["lifetime_cost"] if r["lifetime_cost"] is not None else "N/A",
|
||||
"review_flag": bool(r["review_flag"]),
|
||||
}
|
||||
)
|
||||
return {
|
||||
"title": bundle["title"],
|
||||
"filters_applied": bundle["filters_applied"],
|
||||
"summary": bundle["summary"],
|
||||
"columns": columns,
|
||||
"rows": rows,
|
||||
}
|
||||
|
||||
if canonical_section == "efficiency":
|
||||
columns = [
|
||||
{"key": "group_type", "label": "Group Type"},
|
||||
{"key": "group", "label": "Department / Category"},
|
||||
{"key": "assets_in_scope", "label": "Assets"},
|
||||
{"key": "uptime_pct", "label": "Uptime %"},
|
||||
{"key": "pm_compliance_pct", "label": "PM Compliance %"},
|
||||
{"key": "response_score", "label": "Response Score"},
|
||||
{"key": "repeat_free_score", "label": "Repeat-Free Score"},
|
||||
{"key": "mttr_hours", "label": "MTTR (hrs)"},
|
||||
{"key": "mtbf_display", "label": "MTBF (hrs)"},
|
||||
{"key": "efficiency_score", "label": "Efficiency Score"},
|
||||
]
|
||||
rows = []
|
||||
for r in bundle["rows"]:
|
||||
rows.append(
|
||||
{
|
||||
"group_type": str(r.get("group_type", "")).title(),
|
||||
"group": r.get("group", ""),
|
||||
"assets_in_scope": r.get("assets_in_scope", 0),
|
||||
"uptime_pct": r.get("uptime_pct"),
|
||||
"pm_compliance_pct": r.get("pm_compliance_pct"),
|
||||
"response_score": r.get("response_score"),
|
||||
"repeat_free_score": r.get("repeat_free_score"),
|
||||
"mttr_hours": r.get("mttr_hours") if r.get("mttr_hours") is not None else "—",
|
||||
"mtbf_display": r.get("mtbf_hours") if r.get("mtbf_hours") is not None else "No failures",
|
||||
"efficiency_score": r.get("efficiency_score"),
|
||||
}
|
||||
)
|
||||
return {
|
||||
"title": bundle["title"],
|
||||
"filters_applied": bundle["filters_applied"],
|
||||
"summary": bundle["summary"],
|
||||
"columns": columns,
|
||||
"rows": rows,
|
||||
}
|
||||
|
||||
if canonical_section == "breakdown_frequency":
|
||||
columns = [
|
||||
{"key": "asset_code", "label": "Asset Code"},
|
||||
{"key": "asset_name", "label": "Equipment Name"},
|
||||
{"key": "department_name", "label": "Department"},
|
||||
{"key": "category_name", "label": "Category"},
|
||||
{"key": "breakdown_count", "label": "Breakdowns in Period"},
|
||||
{"key": "avg_downtime_hours", "label": "Avg Downtime (hrs)"},
|
||||
{"key": "repeat_window_count", "label": "Breakdowns in Repeat Window"},
|
||||
{"key": "repeat_failure", "label": "Repeat Failure"},
|
||||
]
|
||||
return {
|
||||
"title": bundle["title"],
|
||||
"filters_applied": bundle["filters_applied"],
|
||||
"summary": bundle["summary"],
|
||||
"columns": columns,
|
||||
"rows": bundle["rows"],
|
||||
}
|
||||
|
||||
# summary
|
||||
columns = [
|
||||
{"key": "metric_id", "label": "Metric ID"},
|
||||
{"key": "label", "label": "Headline Metric"},
|
||||
{"key": "formatted", "label": "Value"},
|
||||
]
|
||||
rows = [
|
||||
{"metric_id": m["id"], "label": m["label"], "formatted": m["formatted"]}
|
||||
for m in bundle.get("metrics", [])
|
||||
]
|
||||
return {
|
||||
"title": bundle["title"],
|
||||
"filters_applied": bundle["filters_applied"],
|
||||
"summary": {
|
||||
"suggestions": len(bundle.get("suggestions", [])),
|
||||
"headline_metrics": len(rows),
|
||||
},
|
||||
"columns": columns,
|
||||
"rows": rows,
|
||||
}
|
||||
|
||||
|
||||
@router.get("/status")
|
||||
def ai_status(
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(*AI_VIEW_ROLES)),
|
||||
):
|
||||
status = get_ai_status(db)
|
||||
# Only system_admin sees provider/model internals; other roles get only enabled+reachable.
|
||||
if current_user.role != Role.system_admin:
|
||||
return {
|
||||
"enabled": status["enabled"],
|
||||
"ai_enabled_setting": status["ai_enabled_setting"],
|
||||
"provider": None,
|
||||
"model": None,
|
||||
"reachable": status["reachable"],
|
||||
}
|
||||
return status
|
||||
|
||||
|
||||
@router.get("/summary")
|
||||
def ai_summary(
|
||||
params: dict[str, Any] = Depends(_ai_query_params),
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(*AI_VIEW_ROLES)),
|
||||
):
|
||||
return _build_section_bundle(db, current_user, "summary", params)
|
||||
|
||||
|
||||
@router.get("/comparison")
|
||||
def ai_comparison(
|
||||
params: dict[str, Any] = Depends(_ai_query_params),
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(*AI_VIEW_ROLES)),
|
||||
):
|
||||
return _build_section_bundle(db, current_user, "comparison", params)
|
||||
|
||||
|
||||
@router.get("/depreciation")
|
||||
def ai_depreciation(
|
||||
params: dict[str, Any] = Depends(_ai_query_params),
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(*AI_VIEW_ROLES)),
|
||||
):
|
||||
return _build_section_bundle(db, current_user, "depreciation", params)
|
||||
|
||||
|
||||
@router.get("/efficiency")
|
||||
def ai_efficiency(
|
||||
params: dict[str, Any] = Depends(_ai_query_params),
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(*AI_VIEW_ROLES)),
|
||||
):
|
||||
return _build_section_bundle(db, current_user, "efficiency", params)
|
||||
|
||||
|
||||
@router.get("/breakdown-frequency")
|
||||
def ai_breakdown_frequency(
|
||||
params: dict[str, Any] = Depends(_ai_query_params),
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(*AI_VIEW_ROLES)),
|
||||
):
|
||||
return _build_section_bundle(db, current_user, "breakdown_frequency", params)
|
||||
|
||||
|
||||
@router.get("/suggestions")
|
||||
def ai_suggestions(
|
||||
params: dict[str, Any] = Depends(_ai_query_params),
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(*AI_VIEW_ROLES)),
|
||||
):
|
||||
dataset = _load_scoped_dataset(db, current_user, params)
|
||||
echo = _filters_echo(dataset, params)
|
||||
res = generate_suggestions(dataset)
|
||||
return {
|
||||
"period_start": str(dataset["period_start"]),
|
||||
"period_end": str(dataset["period_end"]),
|
||||
"filters_applied": echo,
|
||||
"total": len(res["suggestions"]),
|
||||
"suggestions": res["suggestions"],
|
||||
"evidence": res["evidence"],
|
||||
}
|
||||
|
||||
|
||||
@router.post("/narrative/regenerate")
|
||||
def ai_regenerate_narrative(
|
||||
body: RegenerateNarrativeRequest,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(Role.system_admin)),
|
||||
):
|
||||
canonical = SECTION_ALIASES.get((body.section or "").strip().lower())
|
||||
if not canonical:
|
||||
raise HTTPException(
|
||||
status_code=400,
|
||||
detail=f"Unknown AI section '{body.section}'. Expected one of: summary, comparison, depreciation, efficiency, breakdown-frequency.",
|
||||
)
|
||||
params = {
|
||||
"period": body.filters.get("period", "12m"),
|
||||
"date_from": body.filters.get("date_from"),
|
||||
"date_to": body.filters.get("date_to"),
|
||||
"department_id": body.filters.get("department_id"),
|
||||
"category_id": body.filters.get("category_id"),
|
||||
}
|
||||
bundle = _build_section_bundle(db, current_user, canonical, params, force_regenerate=True)
|
||||
return {
|
||||
"section": canonical,
|
||||
"narrative": bundle["narrative"],
|
||||
}
|
||||
|
||||
|
||||
@router.get("/{section}/export")
|
||||
def ai_export_section(
|
||||
section: str,
|
||||
format: Literal["xlsx", "csv"] = Query("xlsx"),
|
||||
params: dict[str, Any] = Depends(_ai_query_params),
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(*AI_VIEW_ROLES)),
|
||||
):
|
||||
canonical = SECTION_ALIASES.get((section or "").strip().lower())
|
||||
if not canonical:
|
||||
raise HTTPException(status_code=404, detail=f"Unknown AI report section '{section}'.")
|
||||
|
||||
bundle = _build_section_bundle(db, current_user, canonical, params)
|
||||
export_payload = _build_export_payload(canonical, bundle)
|
||||
if format == "csv":
|
||||
buf = build_csv(export_payload)
|
||||
media_type = "text/csv; charset=utf-8"
|
||||
else:
|
||||
buf = build_ai_xlsx(
|
||||
export_payload,
|
||||
evidence=bundle.get("metrics", []),
|
||||
how_calculated=bundle.get("how_calculated", {}),
|
||||
)
|
||||
media_type = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
|
||||
|
||||
filename = f"ai-{canonical.replace('_', '-')}.{format}"
|
||||
return StreamingResponse(
|
||||
buf,
|
||||
media_type=media_type,
|
||||
headers={
|
||||
"Content-Disposition": f'attachment; filename="{filename}"',
|
||||
},
|
||||
)
|
||||
|
||||
@@ -0,0 +1,967 @@
|
||||
from datetime import date
|
||||
from typing import Any, Optional
|
||||
from fastapi import APIRouter, Depends, File, HTTPException, Query, UploadFile, status
|
||||
from fastapi.responses import StreamingResponse
|
||||
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,
|
||||
CoverageOut,
|
||||
InsuranceSummaryOut,
|
||||
PMRecordSummaryOut,
|
||||
PMScheduleSummaryOut,
|
||||
WarrantySummaryOut,
|
||||
)
|
||||
from ..services.asset_import import build_import_template_xlsx, process_asset_import
|
||||
from ..services.audit import log_audit
|
||||
from ..services.calculations import compute_schedule_status, coverage_status
|
||||
from ..services.coverage import get_coverage, get_coverage_map
|
||||
from ..services.permissions import Role, maybe_strip_costs_response
|
||||
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",
|
||||
get_setting_value(db, "calibration_lead_days", 15),
|
||||
)
|
||||
),
|
||||
"pm": int(get_setting_value(db, "pm_due_window_days")),
|
||||
"pm_in_house": int(get_setting_value(db, "pm_inhouse_lead_days", 15)),
|
||||
"pm_outsourced": int(get_setting_value(db, "pm_outsourced_lead_days", 15)),
|
||||
"red": int(get_setting_value(db, "red_threshold_days", 7)),
|
||||
}
|
||||
|
||||
|
||||
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],
|
||||
cov: dict[str, Any] | None = None,
|
||||
) -> AssetOut:
|
||||
d = _derive_asset_fields(asset, rels, today, leads)
|
||||
cov_out = CoverageOut(**cov) if cov is not None else None
|
||||
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,
|
||||
acquisition_mode=asset.acquisition_mode or "purchased",
|
||||
monthly_rent=asset.monthly_rent,
|
||||
useful_life_years=asset.useful_life_years,
|
||||
salvage_pct=asset.salvage_pct,
|
||||
depreciation_method=asset.depreciation_method,
|
||||
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"],
|
||||
coverage_tag=cov_out.tag if cov_out else "out_of_contract",
|
||||
coverage=cov_out,
|
||||
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()
|
||||
asset_ids = [a.id for a in rows]
|
||||
rels = _preload_latest_relations(db, asset_ids)
|
||||
today = effective_today(db)
|
||||
leads = _lead_settings(db)
|
||||
cov_map = get_coverage_map(db, asset_ids, today)
|
||||
|
||||
items: list[AssetLookupOut] = []
|
||||
for a in rows:
|
||||
d = _derive_asset_fields(a, rels, today, leads)
|
||||
cov = cov_map.get(a.id)
|
||||
cov_out = CoverageOut(**cov) if cov is not None else None
|
||||
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,
|
||||
coverage_tag=cov_out.tag if cov_out else "out_of_contract",
|
||||
coverage=cov_out,
|
||||
)
|
||||
)
|
||||
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,
|
||||
requires_calibration: Optional[bool] = None,
|
||||
insurance_applicable: Optional[bool] = 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 requires_calibration is not None:
|
||||
query = query.filter(Asset.requires_calibration.is_(requires_calibration))
|
||||
if insurance_applicable is not None:
|
||||
query = query.filter(Asset.insurance_applicable.is_(insurance_applicable))
|
||||
|
||||
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()
|
||||
asset_ids = [a.id for a in rows]
|
||||
rels = _preload_latest_relations(db, asset_ids)
|
||||
today = effective_today(db)
|
||||
leads = _lead_settings(db)
|
||||
cov_map = get_coverage_map(db, asset_ids, today)
|
||||
|
||||
out_items = [_to_asset_out(a, rels, today, leads, cov_map.get(a.id)) 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 maybe_strip_costs_response({"items": out_items, "total": total}, current_user.role)
|
||||
|
||||
|
||||
@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,
|
||||
acquisition_mode=payload.acquisition_mode,
|
||||
monthly_rent=payload.monthly_rent,
|
||||
useful_life_years=payload.useful_life_years,
|
||||
salvage_pct=payload.salvage_pct,
|
||||
depreciation_method=payload.depreciation_method,
|
||||
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)
|
||||
today = effective_today(db)
|
||||
rels = _preload_latest_relations(db, [asset.id])
|
||||
cov = get_coverage(db, asset.id, today)
|
||||
return _to_asset_out(loaded, rels, today, _lead_settings(db), cov)
|
||||
|
||||
|
||||
@router.get("/import-template")
|
||||
def download_asset_import_template(
|
||||
db: Session = Depends(get_db),
|
||||
_user: User = Depends(require_roles(Role.system_admin, Role.biomedical)),
|
||||
):
|
||||
buf = build_import_template_xlsx(db)
|
||||
return StreamingResponse(
|
||||
buf,
|
||||
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
headers={
|
||||
"Content-Disposition": 'attachment; filename="asset_import_template.xlsx"',
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@router.post("/bulk-import")
|
||||
def bulk_import_assets(
|
||||
file: UploadFile = File(...),
|
||||
dry_run: bool = Query(False),
|
||||
skip_invalid: bool = Query(False),
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical)),
|
||||
):
|
||||
content = file.file.read()
|
||||
return process_asset_import(
|
||||
db=db,
|
||||
filename=file.filename or "upload.xlsx",
|
||||
content=content,
|
||||
user_id=current_user.id,
|
||||
dry_run=dry_run,
|
||||
skip_invalid=skip_invalid,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/{asset_id}/coverage", response_model=CoverageOut)
|
||||
def get_asset_coverage(
|
||||
asset_id: int,
|
||||
on_date: Optional[date] = None,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user),
|
||||
):
|
||||
asset = db.query(Asset).filter(Asset.id == asset_id).first()
|
||||
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.",
|
||||
)
|
||||
return CoverageOut(**get_coverage(db, asset.id, on_date or effective_today(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.")
|
||||
|
||||
today = effective_today(db)
|
||||
rels = _preload_latest_relations(db, [asset.id])
|
||||
cov = get_coverage(db, asset.id, today)
|
||||
return maybe_strip_costs_response(
|
||||
_to_asset_out(asset, rels, today, _lead_settings(db), cov),
|
||||
current_user.role,
|
||||
)
|
||||
|
||||
|
||||
@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)
|
||||
today = effective_today(db)
|
||||
rels = _preload_latest_relations(db, [asset.id])
|
||||
cov = get_coverage(db, asset.id, today)
|
||||
return _to_asset_out(loaded, rels, today, _lead_settings(db), cov)
|
||||
|
||||
|
||||
@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])
|
||||
cov = get_coverage(db, asset.id, today)
|
||||
asset_out = _to_asset_out(asset, rels, today, leads, cov)
|
||||
|
||||
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,
|
||||
contract_value=c.contract_value,
|
||||
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,
|
||||
cost_per_visit=s.cost_per_visit,
|
||||
next_planned_date=s.next_planned_date,
|
||||
is_active=s.is_active,
|
||||
)
|
||||
for s in pm_sched_rows
|
||||
]
|
||||
|
||||
pm_rec_rows = (
|
||||
db.query(PMRecord)
|
||||
.options(joinedload(PMRecord.schedule))
|
||||
.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:
|
||||
pm_lead = (
|
||||
leads["pm_in_house"]
|
||||
if r.schedule and r.schedule.service_mode == "in_house"
|
||||
else leads["pm_outsourced"]
|
||||
)
|
||||
st, sev = compute_schedule_status(r.planned_date, r.status, today, pm_lead, 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
|
||||
]
|
||||
|
||||
overview = AssetOverviewOut(
|
||||
asset=asset_out,
|
||||
coverage=CoverageOut(**cov),
|
||||
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,
|
||||
)
|
||||
return maybe_strip_costs_response(overview, current_user.role)
|
||||
@@ -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)
|
||||
@@ -0,0 +1,82 @@
|
||||
from datetime import date, datetime, time, timedelta, timezone
|
||||
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
from sqlalchemy import String, cast, or_
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..core.db import get_db
|
||||
from ..core.deps import require_roles
|
||||
from ..core.time_utils import KOLKATA
|
||||
from ..models import AuditLog, User
|
||||
from ..services.permissions import Role
|
||||
|
||||
router = APIRouter(prefix="/audit-logs", tags=["audit"])
|
||||
|
||||
|
||||
@router.get("")
|
||||
def list_audit_logs(
|
||||
entity_type: str | None = Query(None),
|
||||
by_user_id: int | None = Query(None),
|
||||
action: str | None = Query(None),
|
||||
date_from: date | None = Query(None),
|
||||
date_to: date | None = Query(None),
|
||||
q: str | None = Query(None),
|
||||
page: int = Query(1, ge=1),
|
||||
page_size: int = Query(100, ge=1, le=500),
|
||||
db: Session = Depends(get_db),
|
||||
_admin: User = Depends(require_roles(Role.system_admin)),
|
||||
):
|
||||
query = db.query(AuditLog, User.name).outerjoin(User, AuditLog.by_user_id == User.id)
|
||||
|
||||
if entity_type:
|
||||
query = query.filter(AuditLog.entity_type == entity_type.strip())
|
||||
if by_user_id is not None:
|
||||
query = query.filter(AuditLog.by_user_id == by_user_id)
|
||||
if action:
|
||||
query = query.filter(AuditLog.action == action.strip())
|
||||
if date_from is not None:
|
||||
dt_from_utc = KOLKATA.localize(
|
||||
datetime.combine(date_from, time(0, 0, 0))
|
||||
).astimezone(timezone.utc)
|
||||
query = query.filter(AuditLog.at >= dt_from_utc)
|
||||
if date_to is not None:
|
||||
dt_to_utc = KOLKATA.localize(
|
||||
datetime.combine(date_to + timedelta(days=1), time(0, 0, 0))
|
||||
).astimezone(timezone.utc)
|
||||
query = query.filter(AuditLog.at < dt_to_utc)
|
||||
if q and q.strip():
|
||||
pat = f"%{q.strip()}%"
|
||||
query = query.filter(
|
||||
or_(
|
||||
AuditLog.entity_type.ilike(pat),
|
||||
AuditLog.action.ilike(pat),
|
||||
AuditLog.changes_json.ilike(pat),
|
||||
cast(AuditLog.entity_id, String).ilike(pat),
|
||||
User.name.ilike(pat),
|
||||
)
|
||||
)
|
||||
|
||||
total = query.count()
|
||||
rows = (
|
||||
query.order_by(AuditLog.at.desc(), AuditLog.id.desc())
|
||||
.offset((page - 1) * page_size)
|
||||
.limit(page_size)
|
||||
.all()
|
||||
)
|
||||
|
||||
return {
|
||||
"items": [
|
||||
{
|
||||
"id": log.id,
|
||||
"entity_type": log.entity_type,
|
||||
"entity_id": log.entity_id,
|
||||
"action": log.action,
|
||||
"changes_json": log.changes_json,
|
||||
"by_user_id": log.by_user_id,
|
||||
"by_user_name": user_name or "System",
|
||||
"at": log.at,
|
||||
}
|
||||
for log, user_name in rows
|
||||
],
|
||||
"total": total,
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
from collections import defaultdict, deque
|
||||
import threading
|
||||
import time
|
||||
from fastapi import APIRouter, Depends, HTTPException, Request, status
|
||||
from sqlalchemy.orm import Session, joinedload
|
||||
from ..core.db import get_db
|
||||
from ..core.deps import get_current_user
|
||||
from ..core.exceptions import CodedHTTPException
|
||||
from ..core.security import create_access_token, hash_password, validate_password, verify_password
|
||||
from ..models.masters import User
|
||||
from ..schemas.auth import LoginRequest, TokenResponse, UserOut
|
||||
from ..services.settings_service import get_demo_as_of_date
|
||||
from pydantic import BaseModel, Field
|
||||
|
||||
router = APIRouter(prefix="/auth", tags=["auth"])
|
||||
|
||||
|
||||
class ChangePasswordRequest(BaseModel):
|
||||
current_password: str
|
||||
new_password: str = Field(..., max_length=128)
|
||||
|
||||
MAX_LOGIN_ATTEMPTS = 15
|
||||
LOGIN_WINDOW_SECONDS = 60.0
|
||||
_login_attempts: dict[str, deque[float]] = defaultdict(deque)
|
||||
_rate_limit_lock = threading.Lock()
|
||||
|
||||
|
||||
def reset_login_rate_limiter() -> None:
|
||||
"""Clear sliding-window login attempt counters (used in tests)."""
|
||||
with _rate_limit_lock:
|
||||
_login_attempts.clear()
|
||||
|
||||
|
||||
def _enforce_login_rate_limit(client_ip: str, email_norm: str) -> None:
|
||||
now = time.monotonic()
|
||||
cutoff = now - LOGIN_WINDOW_SECONDS
|
||||
key = f"{client_ip}:{email_norm}"
|
||||
with _rate_limit_lock:
|
||||
attempts = _login_attempts[key]
|
||||
while attempts and attempts[0] <= cutoff:
|
||||
attempts.popleft()
|
||||
if len(attempts) >= MAX_LOGIN_ATTEMPTS:
|
||||
raise CodedHTTPException(
|
||||
status_code=status.HTTP_429_TOO_MANY_REQUESTS,
|
||||
detail="Too many login attempts. Please wait a minute.",
|
||||
code="RATE_LIMITED",
|
||||
)
|
||||
attempts.append(now)
|
||||
|
||||
|
||||
def _build_user_out(user: User, db: Session) -> UserOut:
|
||||
return UserOut(
|
||||
id=user.id,
|
||||
name=user.name,
|
||||
email=user.email,
|
||||
role=user.role,
|
||||
department_id=user.department_id,
|
||||
department_name=user.department.name if user.department else None,
|
||||
is_active=user.is_active,
|
||||
demo_as_of_date=get_demo_as_of_date(db),
|
||||
)
|
||||
|
||||
|
||||
@router.post("/login", response_model=TokenResponse)
|
||||
def login(payload: LoginRequest, request: Request, db: Session = Depends(get_db)):
|
||||
email_norm = payload.email.strip().lower()
|
||||
client_ip = request.client.host if request.client else "unknown"
|
||||
_enforce_login_rate_limit(client_ip, email_norm)
|
||||
user = (
|
||||
db.query(User)
|
||||
.options(joinedload(User.department))
|
||||
.filter(User.email == email_norm)
|
||||
.first()
|
||||
)
|
||||
if user is None or not verify_password(payload.password, user.password_hash):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_401_UNAUTHORIZED,
|
||||
detail="Invalid email or password.",
|
||||
)
|
||||
if not user.is_active:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="User account is inactive.",
|
||||
)
|
||||
|
||||
token = create_access_token({
|
||||
"sub": str(user.id),
|
||||
"role": user.role,
|
||||
"tv": user.token_version,
|
||||
})
|
||||
return TokenResponse(
|
||||
access_token=token,
|
||||
token_type="bearer",
|
||||
user=_build_user_out(user, db),
|
||||
)
|
||||
|
||||
|
||||
@router.get("/me", response_model=UserOut)
|
||||
def get_me(
|
||||
current_user: User = Depends(get_current_user),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
return _build_user_out(current_user, db)
|
||||
|
||||
|
||||
@router.post("/change-password")
|
||||
def change_password(
|
||||
payload: ChangePasswordRequest,
|
||||
current_user: User = Depends(get_current_user),
|
||||
db: Session = Depends(get_db),
|
||||
):
|
||||
if not verify_password(payload.current_password, current_user.password_hash):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Current password is incorrect.",
|
||||
)
|
||||
if payload.new_password == payload.current_password:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="New password must be different.",
|
||||
)
|
||||
validate_password(payload.new_password, email=current_user.email)
|
||||
current_user.password_hash = hash_password(payload.new_password)
|
||||
current_user.token_version = (current_user.token_version or 0) + 1
|
||||
db.commit()
|
||||
db.refresh(current_user)
|
||||
|
||||
new_token = create_access_token({
|
||||
"sub": str(current_user.id),
|
||||
"role": current_user.role,
|
||||
"tv": current_user.token_version,
|
||||
})
|
||||
return {
|
||||
"message": "Password changed successfully.",
|
||||
"access_token": new_token,
|
||||
"token_type": "bearer",
|
||||
}
|
||||
@@ -0,0 +1,682 @@
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
from fastapi import APIRouter, Body, Depends, File, HTTPException, Query, UploadFile, status
|
||||
from fastapi.responses import StreamingResponse
|
||||
from sqlalchemy import or_
|
||||
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 add_months, effective_today
|
||||
from ..models import Asset, CalibrationPlan, CalibrationRecord, User, Vendor
|
||||
from ..schemas.calibration import (
|
||||
CalibrationPlanApproveIn,
|
||||
CalibrationPlanBulkCreateIn,
|
||||
CalibrationPlanBulkOut,
|
||||
CalibrationPlanCreateFromAsset,
|
||||
CalibrationPlanListOut,
|
||||
CalibrationPlanOut,
|
||||
CalibrationPlanUpdateIn,
|
||||
CalibrationRecordCompleteIn,
|
||||
CalibrationRecordCompleteOut,
|
||||
CalibrationRecordListOut,
|
||||
CalibrationRecordOut,
|
||||
CalibrationRecordSummaryCounts,
|
||||
CalibrationStatusFilter,
|
||||
)
|
||||
from ..services.audit import log_audit
|
||||
from ..services.bulk_templates import build_calibration_template_xlsx, process_calibration_import
|
||||
from ..services.calculations import compute_schedule_status
|
||||
from ..services.permissions import Role
|
||||
from ..services.settings_service import get_setting_value
|
||||
|
||||
router = APIRouter(prefix="/calibration", tags=["calibration"])
|
||||
|
||||
APPROVER_ROLES = {Role.management.value, Role.system_admin.value, Role.coordinator.value}
|
||||
|
||||
|
||||
def _cal_lead_settings(db: Session) -> dict[str, int]:
|
||||
return {
|
||||
"lead": int(
|
||||
get_setting_value(
|
||||
db,
|
||||
"calibration_due_window_days",
|
||||
get_setting_value(db, "calibration_lead_days", 15),
|
||||
)
|
||||
),
|
||||
"red": int(get_setting_value(db, "red_threshold_days", 7)),
|
||||
}
|
||||
|
||||
|
||||
def _default_per_year(frequency_months: int) -> int:
|
||||
return max(1, round(12 / frequency_months))
|
||||
|
||||
|
||||
def _to_plan_out(plan: CalibrationPlan) -> CalibrationPlanOut:
|
||||
asset = plan.asset
|
||||
return CalibrationPlanOut(
|
||||
id=plan.id,
|
||||
asset_id=plan.asset_id,
|
||||
asset_code=asset.asset_code,
|
||||
asset_name=asset.name,
|
||||
department_id=asset.department_id,
|
||||
department_name=asset.department.name if asset.department else None,
|
||||
frequency_months=plan.frequency_months,
|
||||
calibrations_per_year=plan.calibrations_per_year,
|
||||
agency_id=plan.agency_id,
|
||||
agency_name=plan.agency.name if plan.agency else None,
|
||||
approved_by_id=plan.approved_by_id,
|
||||
approved_by_name=plan.approved_by.name if plan.approved_by else None,
|
||||
approved_on=plan.approved_on,
|
||||
next_due_date=plan.next_due_date,
|
||||
is_active=plan.is_active,
|
||||
)
|
||||
|
||||
|
||||
def _to_record_out(
|
||||
rec: CalibrationRecord,
|
||||
today: date,
|
||||
leads: dict[str, int],
|
||||
) -> CalibrationRecordOut:
|
||||
asset = rec.asset
|
||||
plan = rec.plan
|
||||
if rec.status == "completed":
|
||||
comp_status, severity = "completed", "ok"
|
||||
else:
|
||||
comp_status, severity = compute_schedule_status(
|
||||
rec.due_date, None, today, leads["lead"], leads["red"]
|
||||
)
|
||||
return CalibrationRecordOut(
|
||||
id=rec.id,
|
||||
plan_id=rec.plan_id,
|
||||
asset_id=rec.asset_id,
|
||||
asset_code=asset.asset_code,
|
||||
asset_name=asset.name,
|
||||
department_id=asset.department_id,
|
||||
department_name=asset.department.name if asset.department else None,
|
||||
location_name=asset.location.name if asset.location else None,
|
||||
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=comp_status,
|
||||
severity=severity,
|
||||
frequency_months=plan.frequency_months,
|
||||
approved_by_name=plan.approved_by.name if plan.approved_by else None,
|
||||
approved_on=plan.approved_on,
|
||||
)
|
||||
|
||||
|
||||
def _load_plan_with_joins(db: Session, plan_id: int) -> CalibrationPlan | None:
|
||||
return (
|
||||
db.query(CalibrationPlan)
|
||||
.options(
|
||||
joinedload(CalibrationPlan.asset).joinedload(Asset.department),
|
||||
joinedload(CalibrationPlan.agency),
|
||||
joinedload(CalibrationPlan.approved_by),
|
||||
)
|
||||
.filter(CalibrationPlan.id == plan_id)
|
||||
.first()
|
||||
)
|
||||
|
||||
|
||||
def _load_record_with_joins(db: Session, record_id: int) -> CalibrationRecord | None:
|
||||
return (
|
||||
db.query(CalibrationRecord)
|
||||
.options(
|
||||
joinedload(CalibrationRecord.asset).joinedload(Asset.department),
|
||||
joinedload(CalibrationRecord.asset).joinedload(Asset.location),
|
||||
joinedload(CalibrationRecord.agency),
|
||||
joinedload(CalibrationRecord.plan).joinedload(CalibrationPlan.approved_by),
|
||||
)
|
||||
.filter(CalibrationRecord.id == record_id)
|
||||
.first()
|
||||
)
|
||||
|
||||
|
||||
def _create_plan_and_initial_record(
|
||||
db: Session,
|
||||
*,
|
||||
asset: Asset,
|
||||
frequency_months: int,
|
||||
calibrations_per_year: Optional[int],
|
||||
agency_id: Optional[int],
|
||||
next_due_date: date,
|
||||
approve: bool,
|
||||
current_user: User,
|
||||
today: date,
|
||||
) -> CalibrationPlan:
|
||||
asset.requires_calibration = True
|
||||
asset.updated_by_id = current_user.id
|
||||
|
||||
per_year = calibrations_per_year or _default_per_year(frequency_months)
|
||||
plan = CalibrationPlan(
|
||||
asset_id=asset.id,
|
||||
frequency_months=frequency_months,
|
||||
calibrations_per_year=per_year,
|
||||
agency_id=agency_id,
|
||||
approved_by_id=current_user.id if approve else None,
|
||||
approved_on=today if approve else None,
|
||||
next_due_date=next_due_date,
|
||||
is_active=True,
|
||||
created_by_id=current_user.id,
|
||||
updated_by_id=current_user.id,
|
||||
)
|
||||
db.add(plan)
|
||||
db.flush()
|
||||
|
||||
initial_rec = CalibrationRecord(
|
||||
asset_id=asset.id,
|
||||
plan_id=plan.id,
|
||||
due_date=next_due_date,
|
||||
agency_id=agency_id,
|
||||
status=None,
|
||||
created_by_id=current_user.id,
|
||||
updated_by_id=current_user.id,
|
||||
)
|
||||
db.add(initial_rec)
|
||||
db.flush()
|
||||
|
||||
log_audit(
|
||||
db,
|
||||
entity_type="calibration_plan",
|
||||
entity_id=plan.id,
|
||||
action="create",
|
||||
changes={
|
||||
"asset_id": asset.id,
|
||||
"frequency_months": frequency_months,
|
||||
"calibrations_per_year": per_year,
|
||||
"next_due_date": str(next_due_date),
|
||||
"approved": approve,
|
||||
"initial_record_id": initial_rec.id,
|
||||
},
|
||||
user_id=current_user.id,
|
||||
)
|
||||
return plan
|
||||
|
||||
|
||||
@router.get("/import-template")
|
||||
def download_calibration_import_template(
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.coordinator)),
|
||||
):
|
||||
buf = build_calibration_template_xlsx(db)
|
||||
return StreamingResponse(
|
||||
buf,
|
||||
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
headers={"Content-Disposition": 'attachment; filename="calibration_import_template.xlsx"'},
|
||||
)
|
||||
|
||||
|
||||
@router.post("/bulk-import")
|
||||
def bulk_import_calibration(
|
||||
file: UploadFile = File(...),
|
||||
dry_run: bool = Query(False),
|
||||
skip_invalid: bool = Query(False),
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(
|
||||
require_roles(Role.system_admin, Role.biomedical, Role.coordinator, Role.management)
|
||||
),
|
||||
):
|
||||
content = file.file.read()
|
||||
return process_calibration_import(
|
||||
db=db,
|
||||
filename=file.filename or "calibration.xlsx",
|
||||
content=content,
|
||||
user_id=current_user.id,
|
||||
dry_run=dry_run,
|
||||
skip_invalid=skip_invalid,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/plans", response_model=CalibrationPlanListOut)
|
||||
def list_calibration_plans(
|
||||
q: str = "",
|
||||
department_id: Optional[int] = None,
|
||||
agency_id: Optional[int] = None,
|
||||
is_active: Optional[bool] = None,
|
||||
page: int = Query(1, ge=1),
|
||||
page_size: int = Query(200, ge=1, le=500),
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user),
|
||||
):
|
||||
query = (
|
||||
db.query(CalibrationPlan)
|
||||
.join(Asset, CalibrationPlan.asset_id == Asset.id)
|
||||
.outerjoin(Vendor, CalibrationPlan.agency_id == Vendor.id)
|
||||
.options(
|
||||
joinedload(CalibrationPlan.asset).joinedload(Asset.department),
|
||||
joinedload(CalibrationPlan.agency),
|
||||
joinedload(CalibrationPlan.approved_by),
|
||||
)
|
||||
)
|
||||
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 agency_id is not None:
|
||||
query = query.filter(CalibrationPlan.agency_id == agency_id)
|
||||
if is_active is not None:
|
||||
query = query.filter(CalibrationPlan.is_active.is_(is_active))
|
||||
if q and q.strip():
|
||||
like = f"%{q.strip()}%"
|
||||
query = query.filter(
|
||||
or_(
|
||||
Asset.asset_code.ilike(like),
|
||||
Asset.name.ilike(like),
|
||||
Vendor.name.ilike(like),
|
||||
)
|
||||
)
|
||||
|
||||
total = query.count()
|
||||
rows = (
|
||||
query.order_by(CalibrationPlan.next_due_date.asc(), CalibrationPlan.id.asc())
|
||||
.offset((page - 1) * page_size)
|
||||
.limit(page_size)
|
||||
.all()
|
||||
)
|
||||
return CalibrationPlanListOut(items=[_to_plan_out(p) for p in rows], total=total)
|
||||
|
||||
|
||||
@router.post(
|
||||
"/plans/from-asset/{asset_id}",
|
||||
response_model=CalibrationPlanOut,
|
||||
status_code=status.HTTP_201_CREATED,
|
||||
)
|
||||
def create_calibration_plan_from_asset(
|
||||
asset_id: int,
|
||||
payload: CalibrationPlanCreateFromAsset,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(
|
||||
require_roles(Role.system_admin, Role.biomedical, Role.coordinator, Role.management)
|
||||
),
|
||||
):
|
||||
asset = db.query(Asset).filter(Asset.id == asset_id).first()
|
||||
if asset is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Asset not found.")
|
||||
|
||||
existing = db.query(CalibrationPlan.id).filter(CalibrationPlan.asset_id == asset_id).first()
|
||||
if existing is not None:
|
||||
raise CodedHTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail="Calibration plan already exists for this asset.",
|
||||
code="DUPLICATE_CALIBRATION_PLAN",
|
||||
)
|
||||
|
||||
if payload.approve and current_user.role not in APPROVER_ROLES:
|
||||
raise CodedHTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Only management, system_admin, or coordinator can approve calibration frequency.",
|
||||
code="FORBIDDEN_CALIBRATION_APPROVAL",
|
||||
)
|
||||
|
||||
if payload.agency_id is not None:
|
||||
if not db.query(Vendor.id).filter(Vendor.id == payload.agency_id).first():
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Calibration agency not found.")
|
||||
|
||||
today = effective_today(db)
|
||||
plan = _create_plan_and_initial_record(
|
||||
db,
|
||||
asset=asset,
|
||||
frequency_months=payload.frequency_months,
|
||||
calibrations_per_year=payload.calibrations_per_year,
|
||||
agency_id=payload.agency_id,
|
||||
next_due_date=payload.next_due_date,
|
||||
approve=payload.approve,
|
||||
current_user=current_user,
|
||||
today=today,
|
||||
)
|
||||
db.commit()
|
||||
|
||||
loaded = _load_plan_with_joins(db, plan.id)
|
||||
return _to_plan_out(loaded)
|
||||
|
||||
|
||||
@router.post("/plans/bulk-from-assets", response_model=CalibrationPlanBulkOut)
|
||||
def bulk_create_calibration_plans(
|
||||
payload: CalibrationPlanBulkCreateIn,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(
|
||||
require_roles(Role.system_admin, Role.biomedical, Role.coordinator, Role.management)
|
||||
),
|
||||
):
|
||||
if payload.approve and current_user.role not in APPROVER_ROLES:
|
||||
raise CodedHTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Only management, system_admin, or coordinator can approve calibration frequency.",
|
||||
code="FORBIDDEN_CALIBRATION_APPROVAL",
|
||||
)
|
||||
|
||||
if payload.agency_id is not None:
|
||||
if not db.query(Vendor.id).filter(Vendor.id == payload.agency_id).first():
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Calibration agency not found.")
|
||||
|
||||
unique_ids = list(dict.fromkeys(payload.asset_ids))
|
||||
assets_by_id = {a.id: a for a in db.query(Asset).filter(Asset.id.in_(unique_ids)).all()}
|
||||
existing_asset_ids = {
|
||||
row[0]
|
||||
for row in db.query(CalibrationPlan.asset_id)
|
||||
.filter(CalibrationPlan.asset_id.in_(unique_ids))
|
||||
.all()
|
||||
}
|
||||
|
||||
today = effective_today(db)
|
||||
created_ids: list[int] = []
|
||||
skipped_ids: list[int] = []
|
||||
|
||||
for aid in unique_ids:
|
||||
asset = assets_by_id.get(aid)
|
||||
if asset is None or aid in existing_asset_ids:
|
||||
skipped_ids.append(aid)
|
||||
continue
|
||||
plan = _create_plan_and_initial_record(
|
||||
db,
|
||||
asset=asset,
|
||||
frequency_months=payload.frequency_months,
|
||||
calibrations_per_year=payload.calibrations_per_year,
|
||||
agency_id=payload.agency_id,
|
||||
next_due_date=payload.next_due_date,
|
||||
approve=payload.approve,
|
||||
current_user=current_user,
|
||||
today=today,
|
||||
)
|
||||
created_ids.append(plan.id)
|
||||
existing_asset_ids.add(aid)
|
||||
|
||||
db.commit()
|
||||
|
||||
created_out: list[CalibrationPlanOut] = []
|
||||
if created_ids:
|
||||
loaded_plans = (
|
||||
db.query(CalibrationPlan)
|
||||
.options(
|
||||
joinedload(CalibrationPlan.asset).joinedload(Asset.department),
|
||||
joinedload(CalibrationPlan.agency),
|
||||
joinedload(CalibrationPlan.approved_by),
|
||||
)
|
||||
.filter(CalibrationPlan.id.in_(created_ids))
|
||||
.all()
|
||||
)
|
||||
by_id = {p.id: p for p in loaded_plans}
|
||||
created_out = [_to_plan_out(by_id[pid]) for pid in created_ids if pid in by_id]
|
||||
|
||||
return CalibrationPlanBulkOut(created=created_out, skipped_asset_ids=skipped_ids)
|
||||
|
||||
|
||||
@router.put("/plans/{plan_id}", response_model=CalibrationPlanOut)
|
||||
def update_calibration_plan(
|
||||
plan_id: int,
|
||||
payload: CalibrationPlanUpdateIn,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(
|
||||
require_roles(Role.system_admin, Role.biomedical, Role.coordinator, Role.management)
|
||||
),
|
||||
):
|
||||
plan = db.query(CalibrationPlan).filter(CalibrationPlan.id == plan_id).first()
|
||||
if plan is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Calibration plan not found.")
|
||||
|
||||
data = payload.model_dump(exclude_unset=True)
|
||||
|
||||
if current_user.role == Role.biomedical.value:
|
||||
if (
|
||||
("frequency_months" in data and data["frequency_months"] is not None)
|
||||
or ("calibrations_per_year" in data and data["calibrations_per_year"] is not None)
|
||||
):
|
||||
raise CodedHTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Biomedical users cannot modify calibration frequency; management, coordinator, or system_admin approval is required.",
|
||||
code="FORBIDDEN_CALIBRATION_APPROVAL",
|
||||
)
|
||||
|
||||
if "agency_id" in data and data["agency_id"] is not None:
|
||||
if not db.query(Vendor.id).filter(Vendor.id == data["agency_id"]).first():
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Calibration agency not found.")
|
||||
|
||||
if "frequency_months" in data and data["frequency_months"] is not None and "calibrations_per_year" not in data:
|
||||
data["calibrations_per_year"] = _default_per_year(data["frequency_months"])
|
||||
|
||||
old_due_date = plan.next_due_date
|
||||
old_agency_id = plan.agency_id
|
||||
changes: dict[str, dict[str, object]] = {}
|
||||
for k, v in data.items():
|
||||
if v is None and k in ("frequency_months", "calibrations_per_year", "next_due_date", "is_active"):
|
||||
continue
|
||||
old_val = getattr(plan, k)
|
||||
if old_val != v:
|
||||
changes[k] = {"from": old_val, "to": v}
|
||||
setattr(plan, k, v)
|
||||
plan.updated_by_id = current_user.id
|
||||
|
||||
if plan.next_due_date != old_due_date or plan.agency_id != old_agency_id:
|
||||
open_rec = (
|
||||
db.query(CalibrationRecord)
|
||||
.filter(CalibrationRecord.plan_id == plan.id, CalibrationRecord.status.is_(None))
|
||||
.order_by(CalibrationRecord.due_date.desc(), CalibrationRecord.id.desc())
|
||||
.first()
|
||||
)
|
||||
if open_rec is not None:
|
||||
open_rec.due_date = plan.next_due_date
|
||||
open_rec.agency_id = plan.agency_id
|
||||
open_rec.updated_by_id = current_user.id
|
||||
|
||||
if changes:
|
||||
log_audit(
|
||||
db,
|
||||
entity_type="calibration_plan",
|
||||
entity_id=plan.id,
|
||||
action="update",
|
||||
changes=changes,
|
||||
user_id=current_user.id,
|
||||
)
|
||||
db.commit()
|
||||
|
||||
loaded = _load_plan_with_joins(db, plan.id)
|
||||
return _to_plan_out(loaded)
|
||||
|
||||
|
||||
@router.post("/plans/{plan_id}/approve", response_model=CalibrationPlanOut)
|
||||
def approve_calibration_plan(
|
||||
plan_id: int,
|
||||
payload: Optional[CalibrationPlanApproveIn] = Body(default=None),
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(Role.management, Role.system_admin, Role.coordinator)),
|
||||
):
|
||||
plan = db.query(CalibrationPlan).filter(CalibrationPlan.id == plan_id).first()
|
||||
if plan is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Calibration plan not found.")
|
||||
|
||||
today = effective_today(db)
|
||||
changes: dict[str, dict[str, object]] = {}
|
||||
|
||||
if payload is not None:
|
||||
if payload.frequency_months is not None and payload.frequency_months != plan.frequency_months:
|
||||
changes["frequency_months"] = {"from": plan.frequency_months, "to": payload.frequency_months}
|
||||
plan.frequency_months = payload.frequency_months
|
||||
if payload.calibrations_per_year is None:
|
||||
new_per_year = _default_per_year(payload.frequency_months)
|
||||
if new_per_year != plan.calibrations_per_year:
|
||||
changes["calibrations_per_year"] = {"from": plan.calibrations_per_year, "to": new_per_year}
|
||||
plan.calibrations_per_year = new_per_year
|
||||
if payload.calibrations_per_year is not None and payload.calibrations_per_year != plan.calibrations_per_year:
|
||||
changes["calibrations_per_year"] = {"from": plan.calibrations_per_year, "to": payload.calibrations_per_year}
|
||||
plan.calibrations_per_year = payload.calibrations_per_year
|
||||
|
||||
plan.approved_by_id = current_user.id
|
||||
plan.approved_on = today
|
||||
plan.updated_by_id = current_user.id
|
||||
changes["approved_by_id"] = {"to": current_user.id}
|
||||
changes["approved_on"] = {"to": str(today)}
|
||||
|
||||
log_audit(
|
||||
db,
|
||||
entity_type="calibration_plan",
|
||||
entity_id=plan.id,
|
||||
action="approve",
|
||||
changes=changes,
|
||||
user_id=current_user.id,
|
||||
)
|
||||
db.commit()
|
||||
|
||||
loaded = _load_plan_with_joins(db, plan.id)
|
||||
return _to_plan_out(loaded)
|
||||
|
||||
|
||||
@router.get("/records", response_model=CalibrationRecordListOut)
|
||||
def list_calibration_records(
|
||||
q: str = "",
|
||||
department_id: Optional[int] = None,
|
||||
asset_id: Optional[int] = None,
|
||||
agency_id: Optional[int] = None,
|
||||
status_filter: Optional[CalibrationStatusFilter] = Query(None, alias="status"),
|
||||
due_from: Optional[date] = None,
|
||||
due_to: Optional[date] = None,
|
||||
page: int = Query(1, ge=1),
|
||||
page_size: int = Query(200, ge=1, le=500),
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user),
|
||||
):
|
||||
today = effective_today(db)
|
||||
leads = _cal_lead_settings(db)
|
||||
|
||||
query = (
|
||||
db.query(CalibrationRecord)
|
||||
.join(CalibrationPlan, CalibrationRecord.plan_id == CalibrationPlan.id)
|
||||
.join(Asset, CalibrationRecord.asset_id == Asset.id)
|
||||
.outerjoin(Vendor, CalibrationRecord.agency_id == Vendor.id)
|
||||
.options(
|
||||
joinedload(CalibrationRecord.asset).joinedload(Asset.department),
|
||||
joinedload(CalibrationRecord.asset).joinedload(Asset.location),
|
||||
joinedload(CalibrationRecord.agency),
|
||||
joinedload(CalibrationRecord.plan).joinedload(CalibrationPlan.approved_by),
|
||||
)
|
||||
)
|
||||
|
||||
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 asset_id is not None:
|
||||
query = query.filter(CalibrationRecord.asset_id == asset_id)
|
||||
if agency_id is not None:
|
||||
query = query.filter(CalibrationRecord.agency_id == agency_id)
|
||||
if due_from is not None:
|
||||
query = query.filter(CalibrationRecord.due_date >= due_from)
|
||||
if due_to is not None:
|
||||
query = query.filter(CalibrationRecord.due_date <= due_to)
|
||||
|
||||
if q and q.strip():
|
||||
like = f"%{q.strip()}%"
|
||||
query = query.filter(
|
||||
or_(
|
||||
Asset.asset_code.ilike(like),
|
||||
Asset.name.ilike(like),
|
||||
Vendor.name.ilike(like),
|
||||
CalibrationRecord.certificate_no.ilike(like),
|
||||
CalibrationRecord.remarks.ilike(like),
|
||||
)
|
||||
)
|
||||
|
||||
rows = query.order_by(CalibrationRecord.due_date.asc(), CalibrationRecord.id.asc()).all()
|
||||
computed_all = [_to_record_out(r, today, leads) for r in rows]
|
||||
|
||||
summary = CalibrationRecordSummaryCounts(
|
||||
upcoming=sum(1 for item in computed_all if item.status == "upcoming"),
|
||||
due=sum(1 for item in computed_all if item.status == "due"),
|
||||
overdue=sum(1 for item in computed_all if item.status == "overdue"),
|
||||
completed=sum(1 for item in computed_all if item.status == "completed"),
|
||||
)
|
||||
|
||||
if status_filter is not None:
|
||||
filtered = [item for item in computed_all if item.status == status_filter]
|
||||
else:
|
||||
filtered = computed_all
|
||||
|
||||
total = len(filtered)
|
||||
start = (page - 1) * page_size
|
||||
paginated = filtered[start : start + page_size]
|
||||
|
||||
return CalibrationRecordListOut(items=paginated, total=total, summary=summary)
|
||||
|
||||
|
||||
@router.post("/records/{record_id}/complete", response_model=CalibrationRecordCompleteOut)
|
||||
def complete_calibration_record(
|
||||
record_id: int,
|
||||
payload: CalibrationRecordCompleteIn,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.coordinator)),
|
||||
):
|
||||
rec = _load_record_with_joins(db, record_id)
|
||||
if rec is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Calibration record not found.")
|
||||
|
||||
if rec.status == "completed":
|
||||
raise CodedHTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Calibration record is already completed.",
|
||||
code="INVALID_CALIBRATION_STATUS",
|
||||
)
|
||||
|
||||
clean_cert = payload.certificate_no.strip()
|
||||
if not clean_cert:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="certificate_no cannot be blank.",
|
||||
)
|
||||
|
||||
if payload.agency_id is not None:
|
||||
if not db.query(Vendor.id).filter(Vendor.id == payload.agency_id).first():
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Calibration agency not found.")
|
||||
rec.agency_id = payload.agency_id
|
||||
|
||||
rec.status = "completed"
|
||||
rec.completed_date = payload.completed_date
|
||||
rec.certificate_no = clean_cert
|
||||
rec.remarks = payload.remarks.strip() if payload.remarks and payload.remarks.strip() else None
|
||||
rec.updated_by_id = current_user.id
|
||||
|
||||
plan = rec.plan
|
||||
next_due = add_months(payload.completed_date, plan.frequency_months)
|
||||
plan.next_due_date = next_due
|
||||
plan.updated_by_id = current_user.id
|
||||
|
||||
next_rec = CalibrationRecord(
|
||||
asset_id=plan.asset_id,
|
||||
plan_id=plan.id,
|
||||
due_date=next_due,
|
||||
agency_id=rec.agency_id if rec.agency_id is not None else plan.agency_id,
|
||||
status=None,
|
||||
created_by_id=current_user.id,
|
||||
updated_by_id=current_user.id,
|
||||
)
|
||||
db.add(next_rec)
|
||||
db.flush()
|
||||
|
||||
log_audit(
|
||||
db,
|
||||
entity_type="calibration_record",
|
||||
entity_id=rec.id,
|
||||
action="complete",
|
||||
changes={
|
||||
"completed_date": str(payload.completed_date),
|
||||
"certificate_no": clean_cert,
|
||||
"next_due_date": str(next_due),
|
||||
"next_record_id": next_rec.id,
|
||||
},
|
||||
user_id=current_user.id,
|
||||
)
|
||||
db.commit()
|
||||
|
||||
today = effective_today(db)
|
||||
leads = _cal_lead_settings(db)
|
||||
loaded_completed = _load_record_with_joins(db, rec.id)
|
||||
loaded_next = _load_record_with_joins(db, next_rec.id)
|
||||
return CalibrationRecordCompleteOut(
|
||||
completed_record=_to_record_out(loaded_completed, today, leads),
|
||||
next_record=_to_record_out(loaded_next, today, leads),
|
||||
)
|
||||
@@ -0,0 +1,950 @@
|
||||
from datetime import date, datetime, time, timedelta, timezone
|
||||
from typing import Any, Optional
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
||||
from sqlalchemy import or_
|
||||
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 KOLKATA, effective_today, utc_now
|
||||
from ..models import Asset, Complaint, ComplaintEvent, Contract, User, Vendor
|
||||
from ..schemas.assets import CoverageOut
|
||||
from ..schemas.complaints import (
|
||||
ComplaintAssignIn,
|
||||
ComplaintAttendIn,
|
||||
ComplaintCloseIn,
|
||||
ComplaintCorrectTimestampIn,
|
||||
ComplaintCreate,
|
||||
ComplaintEventListOut,
|
||||
ComplaintEventOut,
|
||||
ComplaintListOut,
|
||||
ComplaintOut,
|
||||
ComplaintReopenIn,
|
||||
ComplaintRestoreIn,
|
||||
ComplaintUpdate,
|
||||
)
|
||||
from ..services.audit import log_audit
|
||||
from ..services.calculations import (
|
||||
compute_ce_response_time_minutes,
|
||||
compute_downtime_minutes,
|
||||
compute_response_time_minutes,
|
||||
compute_sla_status,
|
||||
coverage_status,
|
||||
)
|
||||
from ..services.coverage import (
|
||||
format_coverage_tag_label,
|
||||
format_vendor_contact,
|
||||
get_coverage,
|
||||
get_coverage_map,
|
||||
)
|
||||
from ..services.numbering import generate_complaint_no
|
||||
from ..services.permissions import RESTRICTED_COMPLAINT_FIELDS, Role, maybe_strip_costs_response
|
||||
from ..services.settings_service import get_demo_as_of_date, get_setting_value
|
||||
|
||||
router = APIRouter(prefix="/complaints", tags=["complaints"])
|
||||
|
||||
DEPT_USER_EDITABLE_FIELDS = {"description", "breakdown_details", "notes"}
|
||||
|
||||
|
||||
def _norm_utc(dt: datetime | None) -> datetime | None:
|
||||
if dt is None:
|
||||
return None
|
||||
if dt.tzinfo is None:
|
||||
return dt.replace(tzinfo=timezone.utc)
|
||||
return dt.astimezone(timezone.utc)
|
||||
|
||||
|
||||
def _effective_now_utc(db: Session) -> datetime:
|
||||
demo_str = get_demo_as_of_date(db)
|
||||
if demo_str:
|
||||
demo_d = date.fromisoformat(demo_str)
|
||||
real_now_ist = datetime.now(KOLKATA)
|
||||
if demo_d > real_now_ist.date():
|
||||
local_dt = KOLKATA.localize(datetime.combine(demo_d, time(23, 59, 59)))
|
||||
else:
|
||||
local_dt = KOLKATA.localize(datetime.combine(demo_d, real_now_ist.time()))
|
||||
return local_dt.astimezone(timezone.utc)
|
||||
return utc_now()
|
||||
|
||||
|
||||
def _complaint_settings(db: Session) -> tuple[str, str, int, int]:
|
||||
milestone = str(get_setting_value(db, "downtime_end_milestone", "restored_at"))
|
||||
response_start = str(get_setting_value(db, "response_start", "registered_at"))
|
||||
critical_sla = int(get_setting_value(db, "critical_complaint_sla_hours", 4))
|
||||
non_critical_sla = int(get_setting_value(db, "non_critical_complaint_sla_hours", 24))
|
||||
return milestone, response_start, critical_sla, non_critical_sla
|
||||
|
||||
|
||||
def _load_user_names(db: Session, complaints: list[Complaint]) -> dict[int, str]:
|
||||
ids: set[int] = set()
|
||||
for c in complaints:
|
||||
for uid in (
|
||||
c.registered_by_id,
|
||||
c.received_by_id,
|
||||
c.assigned_to_id,
|
||||
c.attended_by_id,
|
||||
c.closed_by_id,
|
||||
):
|
||||
if uid is not None:
|
||||
ids.add(uid)
|
||||
if not ids:
|
||||
return {}
|
||||
return {
|
||||
u.id: u.name
|
||||
for u in db.query(User.id, User.name).filter(User.id.in_(ids)).all()
|
||||
}
|
||||
|
||||
|
||||
def _preload_coverage_refs(
|
||||
db: Session, complaints: list[Complaint]
|
||||
) -> tuple[dict[int, Vendor], dict[int, Contract], dict[int, dict[str, Any]]]:
|
||||
provider_ids = {c.coverage_provider_id for c in complaints if c.coverage_provider_id is not None}
|
||||
contract_ids = {c.coverage_contract_id for c in complaints if c.coverage_contract_id is not None}
|
||||
asset_ids = [c.asset_id for c in complaints]
|
||||
|
||||
vendors_by_id = (
|
||||
{v.id: v for v in db.query(Vendor).filter(Vendor.id.in_(provider_ids)).all()}
|
||||
if provider_ids
|
||||
else {}
|
||||
)
|
||||
contracts_by_id = (
|
||||
{ct.id: ct for ct in db.query(Contract).filter(Contract.id.in_(contract_ids)).all()}
|
||||
if contract_ids
|
||||
else {}
|
||||
)
|
||||
cov_now_map = get_coverage_map(db, asset_ids, effective_today(db))
|
||||
return vendors_by_id, contracts_by_id, cov_now_map
|
||||
|
||||
|
||||
def _build_snapshot_coverage(
|
||||
db: Session,
|
||||
c: Complaint,
|
||||
vendors_by_id: dict[int, Vendor],
|
||||
contracts_by_id: dict[int, Contract],
|
||||
) -> CoverageOut:
|
||||
reg_date = _norm_utc(c.registered_at).astimezone(KOLKATA).date()
|
||||
if c.coverage_tag:
|
||||
provider = vendors_by_id.get(c.coverage_provider_id) if c.coverage_provider_id else None
|
||||
contract = contracts_by_id.get(c.coverage_contract_id) if c.coverage_contract_id else None
|
||||
valid_from = contract.start_date if contract else None
|
||||
valid_until = contract.end_date if contract else None
|
||||
days_left = (valid_until - reg_date).days if valid_until else None
|
||||
if c.coverage_tag == "out_of_contract":
|
||||
sev = "red"
|
||||
elif valid_until is not None:
|
||||
lead = int(get_setting_value(db, "contract_expiry_alert_days", 30))
|
||||
red = int(get_setting_value(db, "contract_critical_alert_days", 7))
|
||||
_, raw_sev = coverage_status(valid_from, valid_until, reg_date, lead, red)
|
||||
sev = raw_sev if raw_sev in ("ok", "yellow", "red") else "ok"
|
||||
else:
|
||||
sev = "ok"
|
||||
return CoverageOut(
|
||||
tag=c.coverage_tag,
|
||||
contract_id=c.coverage_contract_id,
|
||||
warranty_id=None,
|
||||
provider_id=c.coverage_provider_id,
|
||||
provider_name=provider.name if provider else None,
|
||||
provider_contact=format_vendor_contact(provider),
|
||||
valid_from=valid_from,
|
||||
valid_until=valid_until,
|
||||
days_left=days_left,
|
||||
severity=sev,
|
||||
)
|
||||
return CoverageOut(**get_coverage(db, c.asset_id, reg_date))
|
||||
|
||||
|
||||
def _to_complaint_out(
|
||||
c: Complaint,
|
||||
user_names: dict[int, str],
|
||||
milestone: str,
|
||||
response_start: str,
|
||||
now_utc: datetime,
|
||||
critical_sla_hours: int = 4,
|
||||
non_critical_sla_hours: int = 24,
|
||||
coverage_at_registration: CoverageOut | None = None,
|
||||
coverage_now: CoverageOut | None = None,
|
||||
) -> ComplaintOut:
|
||||
reg_at = _norm_utc(c.registered_at)
|
||||
recv_at = _norm_utc(c.received_at)
|
||||
asg_at = _norm_utc(c.assigned_at)
|
||||
att_at = _norm_utc(c.attended_at)
|
||||
rst_at = _norm_utc(c.restored_at)
|
||||
cls_at = _norm_utc(c.closed_at)
|
||||
ce_at = _norm_utc(c.ce_attended_at)
|
||||
upd_at = _norm_utc(c.updated_at)
|
||||
|
||||
resp_min = compute_response_time_minutes(reg_at, recv_at, att_at, response_start=response_start)
|
||||
dt_min, is_ongoing = compute_downtime_minutes(
|
||||
reg_at, att_at, rst_at, cls_at, milestone=milestone, now_utc=now_utc
|
||||
)
|
||||
ce_min = compute_ce_response_time_minutes(reg_at, ce_at)
|
||||
sla_breached, sla_target_hours = compute_sla_status(
|
||||
c.priority,
|
||||
reg_at,
|
||||
att_at,
|
||||
rst_at,
|
||||
critical_sla_hours=critical_sla_hours,
|
||||
non_critical_sla_hours=non_critical_sla_hours,
|
||||
now_utc=now_utc,
|
||||
)
|
||||
|
||||
asset = c.asset
|
||||
return ComplaintOut(
|
||||
id=c.id,
|
||||
complaint_no=c.complaint_no,
|
||||
asset_id=c.asset_id,
|
||||
asset_code=asset.asset_code,
|
||||
asset_name=asset.name,
|
||||
asset_status=asset.status,
|
||||
department_id=asset.department_id,
|
||||
department_name=asset.department.name if asset.department else None,
|
||||
location_name=asset.location.name if asset.location else None,
|
||||
description=c.description,
|
||||
breakdown_details=c.breakdown_details,
|
||||
priority=c.priority,
|
||||
notes=c.notes,
|
||||
registered_at=reg_at,
|
||||
registered_by_id=c.registered_by_id,
|
||||
registered_by_name=user_names.get(c.registered_by_id),
|
||||
received_by_id=c.received_by_id,
|
||||
received_by_name=user_names.get(c.received_by_id),
|
||||
received_at=recv_at,
|
||||
assigned_to_id=c.assigned_to_id,
|
||||
assigned_to_name=user_names.get(c.assigned_to_id) if c.assigned_to_id else None,
|
||||
assigned_team=c.assigned_team,
|
||||
assigned_at=asg_at,
|
||||
attended_by_id=c.attended_by_id,
|
||||
attended_by_name=user_names.get(c.attended_by_id) if c.attended_by_id else None,
|
||||
attended_at=att_at,
|
||||
restored_at=rst_at,
|
||||
closed_by_id=c.closed_by_id,
|
||||
closed_by_name=user_names.get(c.closed_by_id) if c.closed_by_id else None,
|
||||
closed_at=cls_at,
|
||||
call_status=c.call_status,
|
||||
closure_remarks=c.closure_remarks,
|
||||
action_taken=c.action_taken,
|
||||
root_cause=c.root_cause,
|
||||
corrective_action=c.corrective_action,
|
||||
lessons_learned=c.lessons_learned,
|
||||
ce_name=c.ce_name,
|
||||
ce_attended_at=ce_at,
|
||||
ce_action_taken=c.ce_action_taken,
|
||||
spare_required=c.spare_required,
|
||||
spare_details=c.spare_details,
|
||||
spare_cost_estimate=c.spare_cost_estimate,
|
||||
repair_cost=c.repair_cost,
|
||||
coverage_tag=c.coverage_tag or (coverage_at_registration.tag if coverage_at_registration else None),
|
||||
coverage_contract_id=c.coverage_contract_id,
|
||||
coverage_provider_id=c.coverage_provider_id,
|
||||
coverage_at_registration=coverage_at_registration,
|
||||
coverage_now=coverage_now,
|
||||
response_time_minutes=resp_min,
|
||||
downtime_minutes=dt_min,
|
||||
downtime_is_ongoing=is_ongoing,
|
||||
downtime_end_milestone=milestone,
|
||||
response_start_setting=response_start,
|
||||
ce_response_time_minutes=ce_min,
|
||||
sla_target_hours=sla_target_hours,
|
||||
sla_breached=sla_breached,
|
||||
updated_at=upd_at,
|
||||
)
|
||||
|
||||
|
||||
def _load_complaint_or_404(db: Session, complaint_id: int) -> Complaint:
|
||||
comp = (
|
||||
db.query(Complaint)
|
||||
.options(
|
||||
joinedload(Complaint.asset).joinedload(Asset.department),
|
||||
joinedload(Complaint.asset).joinedload(Asset.location),
|
||||
)
|
||||
.filter(Complaint.id == complaint_id)
|
||||
.first()
|
||||
)
|
||||
if comp is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Complaint not found.")
|
||||
return comp
|
||||
|
||||
|
||||
def _check_complaint_visibility(comp: Complaint, user: User) -> None:
|
||||
if user.role == Role.department_user.value and comp.asset.department_id != user.department_id:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Access denied for another department's complaint.",
|
||||
)
|
||||
|
||||
|
||||
def _serialize_one(db: Session, comp: Complaint) -> ComplaintOut:
|
||||
user_names = _load_user_names(db, [comp])
|
||||
milestone, response_start, critical_sla, non_critical_sla = _complaint_settings(db)
|
||||
now_utc = _effective_now_utc(db)
|
||||
vendors_by_id, contracts_by_id, cov_now_map = _preload_coverage_refs(db, [comp])
|
||||
cov_reg = _build_snapshot_coverage(db, comp, vendors_by_id, contracts_by_id)
|
||||
cov_now = CoverageOut(**cov_now_map[comp.asset_id]) if comp.asset_id in cov_now_map else None
|
||||
return _to_complaint_out(
|
||||
comp,
|
||||
user_names,
|
||||
milestone,
|
||||
response_start,
|
||||
now_utc,
|
||||
critical_sla_hours=critical_sla,
|
||||
non_critical_sla_hours=non_critical_sla,
|
||||
coverage_at_registration=cov_reg,
|
||||
coverage_now=cov_now,
|
||||
)
|
||||
|
||||
|
||||
def _sync_asset_status(db: Session, asset: Asset, exclude_complaint_id: int, require_unrestored: bool) -> None:
|
||||
if asset.status != "under_repair":
|
||||
return
|
||||
q = db.query(Complaint.id).filter(
|
||||
Complaint.asset_id == asset.id,
|
||||
Complaint.id != exclude_complaint_id,
|
||||
Complaint.priority == "critical",
|
||||
Complaint.call_status != "closed",
|
||||
)
|
||||
if require_unrestored:
|
||||
q = q.filter(Complaint.restored_at.is_(None))
|
||||
if q.first() is None:
|
||||
asset.status = "in_service"
|
||||
|
||||
|
||||
@router.get("", response_model=ComplaintListOut)
|
||||
def list_complaints(
|
||||
q: Optional[str] = None,
|
||||
department_id: Optional[int] = None,
|
||||
location_id: Optional[int] = None,
|
||||
asset_id: Optional[int] = None,
|
||||
call_status: Optional[str] = None,
|
||||
priority: Optional[str] = None,
|
||||
coverage_tag: Optional[str] = None,
|
||||
assigned_to_id: Optional[int] = None,
|
||||
closure_state: Optional[str] = None,
|
||||
date_from: Optional[str] = None,
|
||||
date_to: Optional[str] = None,
|
||||
page: int = Query(1, ge=1),
|
||||
page_size: int = Query(100, ge=0, le=500),
|
||||
sort: str = "-registered_at",
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user),
|
||||
):
|
||||
query = (
|
||||
db.query(Complaint)
|
||||
.join(Asset, Complaint.asset_id == Asset.id)
|
||||
.options(
|
||||
joinedload(Complaint.asset).joinedload(Asset.department),
|
||||
joinedload(Complaint.asset).joinedload(Asset.location),
|
||||
)
|
||||
)
|
||||
|
||||
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 location_id is not None:
|
||||
query = query.filter(Asset.location_id == location_id)
|
||||
|
||||
if asset_id is not None:
|
||||
query = query.filter(Complaint.asset_id == asset_id)
|
||||
if call_status:
|
||||
query = query.filter(Complaint.call_status == call_status)
|
||||
if priority:
|
||||
query = query.filter(Complaint.priority == priority)
|
||||
if coverage_tag:
|
||||
query = query.filter(Complaint.coverage_tag == coverage_tag)
|
||||
if assigned_to_id is not None:
|
||||
query = query.filter(Complaint.assigned_to_id == assigned_to_id)
|
||||
if closure_state == "open_only":
|
||||
query = query.filter(Complaint.call_status != "closed")
|
||||
elif closure_state == "closed_only":
|
||||
query = query.filter(Complaint.call_status == "closed")
|
||||
|
||||
if date_from:
|
||||
try:
|
||||
d_from = date.fromisoformat(date_from)
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=422, detail="date_from must be YYYY-MM-DD.")
|
||||
start_utc = KOLKATA.localize(datetime.combine(d_from, time(0, 0, 0))).astimezone(timezone.utc)
|
||||
query = query.filter(Complaint.registered_at >= start_utc)
|
||||
|
||||
if date_to:
|
||||
try:
|
||||
d_to = date.fromisoformat(date_to)
|
||||
except ValueError:
|
||||
raise HTTPException(status_code=422, detail="date_to must be YYYY-MM-DD.")
|
||||
end_utc = KOLKATA.localize(
|
||||
datetime.combine(d_to + timedelta(days=1), time(0, 0, 0))
|
||||
).astimezone(timezone.utc)
|
||||
query = query.filter(Complaint.registered_at < end_utc)
|
||||
|
||||
if q and q.strip():
|
||||
like = f"%{q.strip()}%"
|
||||
query = query.filter(
|
||||
or_(
|
||||
Complaint.complaint_no.ilike(like),
|
||||
Complaint.description.ilike(like),
|
||||
Asset.asset_code.ilike(like),
|
||||
Asset.name.ilike(like),
|
||||
)
|
||||
)
|
||||
|
||||
sort_desc = sort.startswith("-")
|
||||
sort_key = sort.lstrip("-")
|
||||
sort_col_map = {
|
||||
"id": Complaint.id,
|
||||
"complaint_no": Complaint.complaint_no,
|
||||
"registered_at": Complaint.registered_at,
|
||||
"priority": Complaint.priority,
|
||||
"call_status": Complaint.call_status,
|
||||
"closed_at": Complaint.closed_at,
|
||||
}
|
||||
col = sort_col_map.get(sort_key, Complaint.registered_at)
|
||||
query = query.order_by(col.desc() if sort_desc else col.asc(), Complaint.id.desc())
|
||||
|
||||
total = query.count()
|
||||
if page_size > 0:
|
||||
query = query.offset((page - 1) * page_size).limit(page_size)
|
||||
rows = query.all()
|
||||
|
||||
user_names = _load_user_names(db, rows)
|
||||
milestone, response_start, critical_sla, non_critical_sla = _complaint_settings(db)
|
||||
now_utc = _effective_now_utc(db)
|
||||
vendors_by_id, contracts_by_id, cov_now_map = _preload_coverage_refs(db, rows)
|
||||
items = [
|
||||
_to_complaint_out(
|
||||
c,
|
||||
user_names,
|
||||
milestone,
|
||||
response_start,
|
||||
now_utc,
|
||||
critical_sla_hours=critical_sla,
|
||||
non_critical_sla_hours=non_critical_sla,
|
||||
coverage_at_registration=_build_snapshot_coverage(db, c, vendors_by_id, contracts_by_id),
|
||||
coverage_now=CoverageOut(**cov_now_map[c.asset_id]) if c.asset_id in cov_now_map else None,
|
||||
)
|
||||
for c in rows
|
||||
]
|
||||
return maybe_strip_costs_response({"items": items, "total": total}, current_user.role)
|
||||
|
||||
|
||||
@router.post("", response_model=ComplaintOut, status_code=status.HTTP_201_CREATED)
|
||||
def create_complaint(
|
||||
payload: ComplaintCreate,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.department_user)),
|
||||
):
|
||||
asset = (
|
||||
db.query(Asset)
|
||||
.options(joinedload(Asset.department), joinedload(Asset.location))
|
||||
.filter(Asset.id == payload.asset_id)
|
||||
.first()
|
||||
)
|
||||
if asset is None:
|
||||
raise HTTPException(status_code=404, detail="Asset not found.")
|
||||
if current_user.role == Role.department_user.value and asset.department_id != current_user.department_id:
|
||||
raise HTTPException(status_code=403, detail="Cannot raise complaint for another department's asset.")
|
||||
|
||||
recv_by_id = payload.received_by_id or current_user.id
|
||||
if payload.received_by_id is not None:
|
||||
if not db.query(User.id).filter(User.id == payload.received_by_id).first():
|
||||
raise HTTPException(status_code=404, detail="Received-by user not found.")
|
||||
|
||||
reg_at = utc_now()
|
||||
recv_at = _norm_utc(payload.received_at) if payload.received_at is not None else reg_at
|
||||
prefix = str(get_setting_value(db, "complaint_no_prefix", "CMP"))
|
||||
cno = generate_complaint_no(db, prefix, reg_at)
|
||||
cov_snapshot = get_coverage(db, asset.id, effective_today(db))
|
||||
|
||||
comp = Complaint(
|
||||
complaint_no=cno,
|
||||
asset_id=asset.id,
|
||||
description=payload.description.strip(),
|
||||
breakdown_details=payload.breakdown_details,
|
||||
priority=payload.priority,
|
||||
notes=payload.notes,
|
||||
assigned_team=payload.assigned_team,
|
||||
registered_at=reg_at,
|
||||
registered_by_id=current_user.id,
|
||||
received_by_id=recv_by_id,
|
||||
received_at=recv_at,
|
||||
call_status="open",
|
||||
coverage_tag=cov_snapshot["tag"],
|
||||
coverage_contract_id=cov_snapshot["contract_id"],
|
||||
coverage_provider_id=cov_snapshot["provider_id"],
|
||||
updated_by_id=current_user.id,
|
||||
)
|
||||
db.add(comp)
|
||||
db.flush()
|
||||
|
||||
if payload.priority == "critical" and bool(
|
||||
get_setting_value(db, "critical_complaint_sets_under_repair", True)
|
||||
):
|
||||
asset.status = "under_repair"
|
||||
asset.updated_by_id = current_user.id
|
||||
|
||||
db.add(
|
||||
ComplaintEvent(
|
||||
complaint_id=comp.id,
|
||||
event_type="registered",
|
||||
from_value=None,
|
||||
to_value="open",
|
||||
by_user_id=current_user.id,
|
||||
at=reg_at,
|
||||
note=payload.notes,
|
||||
)
|
||||
)
|
||||
cov_note = f"Auto-tagged as {format_coverage_tag_label(cov_snapshot['tag'])}"
|
||||
if cov_snapshot.get("provider_name"):
|
||||
cov_note += f" — {cov_snapshot['provider_name']}"
|
||||
db.add(
|
||||
ComplaintEvent(
|
||||
complaint_id=comp.id,
|
||||
event_type="coverage_tagged",
|
||||
from_value=None,
|
||||
to_value=cov_snapshot["tag"],
|
||||
by_user_id=current_user.id,
|
||||
at=reg_at,
|
||||
note=cov_note,
|
||||
)
|
||||
)
|
||||
log_audit(
|
||||
db,
|
||||
entity_type="complaint",
|
||||
entity_id=comp.id,
|
||||
action="create",
|
||||
changes={"complaint_no": cno, "asset_id": asset.id, "priority": payload.priority},
|
||||
user_id=current_user.id,
|
||||
)
|
||||
db.commit()
|
||||
|
||||
loaded = _load_complaint_or_404(db, comp.id)
|
||||
return maybe_strip_costs_response(
|
||||
_serialize_one(db, loaded),
|
||||
current_user.role,
|
||||
status_code=status.HTTP_201_CREATED,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/{complaint_id}", response_model=ComplaintOut)
|
||||
def get_complaint(
|
||||
complaint_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user),
|
||||
):
|
||||
comp = _load_complaint_or_404(db, complaint_id)
|
||||
_check_complaint_visibility(comp, current_user)
|
||||
return maybe_strip_costs_response(_serialize_one(db, comp), current_user.role)
|
||||
|
||||
|
||||
@router.get("/{complaint_id}/events", response_model=ComplaintEventListOut)
|
||||
def get_complaint_events(
|
||||
complaint_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user),
|
||||
):
|
||||
comp = _load_complaint_or_404(db, complaint_id)
|
||||
_check_complaint_visibility(comp, current_user)
|
||||
|
||||
rows = (
|
||||
db.query(ComplaintEvent)
|
||||
.filter(ComplaintEvent.complaint_id == comp.id)
|
||||
.order_by(ComplaintEvent.at.asc(), ComplaintEvent.id.asc())
|
||||
.all()
|
||||
)
|
||||
uid_set = {r.by_user_id for r in rows}
|
||||
user_names = (
|
||||
{u.id: u.name for u in db.query(User.id, User.name).filter(User.id.in_(uid_set)).all()}
|
||||
if uid_set
|
||||
else {}
|
||||
)
|
||||
items = [
|
||||
ComplaintEventOut(
|
||||
id=r.id,
|
||||
complaint_id=r.complaint_id,
|
||||
event_type=r.event_type,
|
||||
from_value=r.from_value,
|
||||
to_value=r.to_value,
|
||||
by_user_id=r.by_user_id,
|
||||
by_user_name=user_names.get(r.by_user_id),
|
||||
at=_norm_utc(r.at),
|
||||
note=r.note,
|
||||
)
|
||||
for r in rows
|
||||
]
|
||||
return {"items": items, "total": len(items)}
|
||||
|
||||
|
||||
@router.patch("/{complaint_id}", response_model=ComplaintOut)
|
||||
def update_complaint(
|
||||
complaint_id: int,
|
||||
payload: ComplaintUpdate,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user),
|
||||
):
|
||||
comp = _load_complaint_or_404(db, complaint_id)
|
||||
fields_sent = payload.model_fields_set
|
||||
|
||||
if RESTRICTED_COMPLAINT_FIELDS & fields_sent and current_user.role not in (
|
||||
Role.system_admin.value,
|
||||
Role.biomedical.value,
|
||||
):
|
||||
raise CodedHTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Only Biomedical or System Admin can edit technical resolution fields.",
|
||||
code="FORBIDDEN_TECHNICAL_FIELDS",
|
||||
)
|
||||
|
||||
if current_user.role in (Role.management.value, Role.coordinator.value):
|
||||
raise CodedHTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="You do not have permission to edit complaints.",
|
||||
code="FORBIDDEN",
|
||||
)
|
||||
|
||||
if current_user.role == Role.department_user.value:
|
||||
_check_complaint_visibility(comp, current_user)
|
||||
if comp.call_status == "closed":
|
||||
raise CodedHTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Closed complaints cannot be edited by department users.",
|
||||
code="FORBIDDEN",
|
||||
)
|
||||
if not fields_sent.issubset(DEPT_USER_EDITABLE_FIELDS):
|
||||
raise CodedHTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Department users can only edit description, breakdown_details, and notes.",
|
||||
code="FORBIDDEN",
|
||||
)
|
||||
|
||||
data = payload.model_dump(exclude_unset=True)
|
||||
if "description" in data and data["description"] is not None:
|
||||
data["description"] = data["description"].strip()
|
||||
if "ce_attended_at" in data and data["ce_attended_at"] is not None:
|
||||
data["ce_attended_at"] = _norm_utc(data["ce_attended_at"])
|
||||
|
||||
changes: dict[str, dict[str, Any]] = {}
|
||||
for k, v in data.items():
|
||||
old_val = getattr(comp, k)
|
||||
if isinstance(old_val, datetime):
|
||||
old_val = _norm_utc(old_val)
|
||||
if old_val != v:
|
||||
changes[k] = {"from": old_val, "to": v}
|
||||
setattr(comp, k, v)
|
||||
comp.updated_by_id = current_user.id
|
||||
|
||||
if changes:
|
||||
now = utc_now()
|
||||
db.add(
|
||||
ComplaintEvent(
|
||||
complaint_id=comp.id,
|
||||
event_type="field_edited",
|
||||
from_value=None,
|
||||
to_value=", ".join(sorted(changes.keys())),
|
||||
by_user_id=current_user.id,
|
||||
at=now,
|
||||
note=f"Updated fields: {', '.join(sorted(changes.keys()))}",
|
||||
)
|
||||
)
|
||||
log_audit(
|
||||
db,
|
||||
entity_type="complaint",
|
||||
entity_id=comp.id,
|
||||
action="update",
|
||||
changes=changes,
|
||||
user_id=current_user.id,
|
||||
)
|
||||
|
||||
db.commit()
|
||||
loaded = _load_complaint_or_404(db, comp.id)
|
||||
return maybe_strip_costs_response(_serialize_one(db, loaded), current_user.role)
|
||||
|
||||
|
||||
@router.post("/{complaint_id}/assign", response_model=ComplaintOut)
|
||||
def assign_complaint(
|
||||
complaint_id: int,
|
||||
payload: ComplaintAssignIn,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical)),
|
||||
):
|
||||
comp = _load_complaint_or_404(db, complaint_id)
|
||||
if payload.assigned_to_id is None and not payload.assigned_team:
|
||||
raise HTTPException(status_code=422, detail="Either assigned_to_id or assigned_team must be provided.")
|
||||
|
||||
assignee: Optional[User] = None
|
||||
target_name = payload.assigned_team or ""
|
||||
if payload.assigned_to_id is not None:
|
||||
assignee = db.query(User).filter(User.id == payload.assigned_to_id, User.is_active.is_(True)).first()
|
||||
if assignee is None:
|
||||
raise HTTPException(status_code=404, detail="Assigned user not found or inactive.")
|
||||
target_name = assignee.name
|
||||
if payload.assigned_team:
|
||||
target_name = f"{assignee.name} ({payload.assigned_team})"
|
||||
|
||||
old_name: Optional[str] = None
|
||||
event_type = "assigned"
|
||||
if comp.assigned_to_id is not None or comp.assigned_team:
|
||||
event_type = "reassigned"
|
||||
if comp.assigned_to_id is not None:
|
||||
old_user = db.query(User.name).filter(User.id == comp.assigned_to_id).first()
|
||||
old_name = old_user[0] if old_user else str(comp.assigned_to_id)
|
||||
if comp.assigned_team:
|
||||
old_name = f"{old_name} ({comp.assigned_team})" if old_name else comp.assigned_team
|
||||
|
||||
now = utc_now()
|
||||
if assignee:
|
||||
comp.assigned_to_id = assignee.id
|
||||
if payload.assigned_team is not None:
|
||||
comp.assigned_team = payload.assigned_team.strip() or None
|
||||
comp.assigned_at = now
|
||||
if comp.call_status == "open":
|
||||
comp.call_status = "in_progress"
|
||||
comp.updated_by_id = current_user.id
|
||||
|
||||
db.add(
|
||||
ComplaintEvent(
|
||||
complaint_id=comp.id,
|
||||
event_type=event_type,
|
||||
from_value=old_name,
|
||||
to_value=target_name,
|
||||
by_user_id=current_user.id,
|
||||
at=now,
|
||||
note=payload.note,
|
||||
)
|
||||
)
|
||||
log_audit(
|
||||
db,
|
||||
entity_type="complaint",
|
||||
entity_id=comp.id,
|
||||
action=event_type,
|
||||
changes={
|
||||
"assigned_to_id": comp.assigned_to_id,
|
||||
"assigned_team": comp.assigned_team,
|
||||
"note": payload.note,
|
||||
},
|
||||
user_id=current_user.id,
|
||||
)
|
||||
db.commit()
|
||||
return _serialize_one(db, _load_complaint_or_404(db, comp.id))
|
||||
|
||||
|
||||
@router.post("/{complaint_id}/attend", response_model=ComplaintOut)
|
||||
def attend_complaint(
|
||||
complaint_id: int,
|
||||
payload: ComplaintAttendIn,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical)),
|
||||
):
|
||||
comp = _load_complaint_or_404(db, complaint_id)
|
||||
att_uid = payload.attended_by_id or current_user.id
|
||||
att_user = db.query(User).filter(User.id == att_uid).first()
|
||||
if att_user is None:
|
||||
raise HTTPException(status_code=404, detail="Attending user not found.")
|
||||
|
||||
now = utc_now()
|
||||
prev_status = comp.call_status
|
||||
comp.attended_by_id = att_user.id
|
||||
comp.attended_at = now
|
||||
if comp.call_status == "open":
|
||||
comp.call_status = "in_progress"
|
||||
comp.updated_by_id = current_user.id
|
||||
|
||||
db.add(
|
||||
ComplaintEvent(
|
||||
complaint_id=comp.id,
|
||||
event_type="attended",
|
||||
from_value=prev_status,
|
||||
to_value=comp.call_status,
|
||||
by_user_id=current_user.id,
|
||||
at=now,
|
||||
note=payload.note or f"Attended by {att_user.name}",
|
||||
)
|
||||
)
|
||||
log_audit(
|
||||
db,
|
||||
entity_type="complaint",
|
||||
entity_id=comp.id,
|
||||
action="attend",
|
||||
changes={"attended_by_id": att_user.id},
|
||||
user_id=current_user.id,
|
||||
)
|
||||
db.commit()
|
||||
return _serialize_one(db, _load_complaint_or_404(db, comp.id))
|
||||
|
||||
|
||||
@router.post("/{complaint_id}/restore", response_model=ComplaintOut)
|
||||
def restore_complaint(
|
||||
complaint_id: int,
|
||||
payload: ComplaintRestoreIn,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical)),
|
||||
):
|
||||
comp = _load_complaint_or_404(db, complaint_id)
|
||||
now = utc_now()
|
||||
comp.restored_at = now
|
||||
comp.updated_by_id = current_user.id
|
||||
|
||||
_sync_asset_status(db, comp.asset, exclude_complaint_id=comp.id, require_unrestored=True)
|
||||
|
||||
db.add(
|
||||
ComplaintEvent(
|
||||
complaint_id=comp.id,
|
||||
event_type="restored",
|
||||
from_value=None,
|
||||
to_value=now.isoformat(),
|
||||
by_user_id=current_user.id,
|
||||
at=now,
|
||||
note=payload.note,
|
||||
)
|
||||
)
|
||||
log_audit(
|
||||
db,
|
||||
entity_type="complaint",
|
||||
entity_id=comp.id,
|
||||
action="restore",
|
||||
changes={"restored_at": now.isoformat()},
|
||||
user_id=current_user.id,
|
||||
)
|
||||
db.commit()
|
||||
return _serialize_one(db, _load_complaint_or_404(db, comp.id))
|
||||
|
||||
|
||||
@router.post("/{complaint_id}/close", response_model=ComplaintOut)
|
||||
def close_complaint(
|
||||
complaint_id: int,
|
||||
payload: ComplaintCloseIn,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical)),
|
||||
):
|
||||
comp = _load_complaint_or_404(db, complaint_id)
|
||||
require_remarks = bool(get_setting_value(db, "require_closure_remarks", True))
|
||||
effective_remarks = (
|
||||
payload.closure_remarks if payload.closure_remarks is not None else comp.closure_remarks
|
||||
)
|
||||
if require_remarks and (effective_remarks is None or not str(effective_remarks).strip()):
|
||||
# Use CodedHTTPException so 422 responses match {"detail": str, "code": str} across the API
|
||||
raise CodedHTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="Closure remarks are required.",
|
||||
code="CLOSURE_REMARKS_REQUIRED",
|
||||
)
|
||||
now = utc_now()
|
||||
prev_status = comp.call_status
|
||||
comp.closed_by_id = current_user.id
|
||||
comp.closed_at = now
|
||||
if comp.restored_at is None:
|
||||
comp.restored_at = comp.closed_at
|
||||
if payload.closure_remarks is not None:
|
||||
comp.closure_remarks = payload.closure_remarks
|
||||
comp.call_status = "closed"
|
||||
comp.updated_by_id = current_user.id
|
||||
|
||||
_sync_asset_status(db, comp.asset, exclude_complaint_id=comp.id, require_unrestored=False)
|
||||
|
||||
db.add(
|
||||
ComplaintEvent(
|
||||
complaint_id=comp.id,
|
||||
event_type="closed",
|
||||
from_value=prev_status,
|
||||
to_value="closed",
|
||||
by_user_id=current_user.id,
|
||||
at=now,
|
||||
note=payload.closure_remarks,
|
||||
)
|
||||
)
|
||||
log_audit(
|
||||
db,
|
||||
entity_type="complaint",
|
||||
entity_id=comp.id,
|
||||
action="close",
|
||||
changes={"call_status": "closed", "closure_remarks": payload.closure_remarks},
|
||||
user_id=current_user.id,
|
||||
)
|
||||
db.commit()
|
||||
return _serialize_one(db, _load_complaint_or_404(db, comp.id))
|
||||
|
||||
|
||||
@router.post("/{complaint_id}/reopen", response_model=ComplaintOut)
|
||||
def reopen_complaint(
|
||||
complaint_id: int,
|
||||
payload: ComplaintReopenIn,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical)),
|
||||
):
|
||||
comp = _load_complaint_or_404(db, complaint_id)
|
||||
now = utc_now()
|
||||
prev_status = comp.call_status
|
||||
comp.closed_at = None
|
||||
comp.closed_by_id = None
|
||||
comp.restored_at = None
|
||||
comp.call_status = "in_progress"
|
||||
comp.updated_by_id = current_user.id
|
||||
|
||||
if comp.priority == "critical" and bool(
|
||||
get_setting_value(db, "critical_complaint_sets_under_repair", True)
|
||||
):
|
||||
comp.asset.status = "under_repair"
|
||||
comp.asset.updated_by_id = current_user.id
|
||||
|
||||
db.add(
|
||||
ComplaintEvent(
|
||||
complaint_id=comp.id,
|
||||
event_type="reopened",
|
||||
from_value=prev_status,
|
||||
to_value="in_progress",
|
||||
by_user_id=current_user.id,
|
||||
at=now,
|
||||
note=payload.reason,
|
||||
)
|
||||
)
|
||||
log_audit(
|
||||
db,
|
||||
entity_type="complaint",
|
||||
entity_id=comp.id,
|
||||
action="reopen",
|
||||
changes={"reason": payload.reason},
|
||||
user_id=current_user.id,
|
||||
)
|
||||
db.commit()
|
||||
return _serialize_one(db, _load_complaint_or_404(db, comp.id))
|
||||
|
||||
|
||||
@router.post("/{complaint_id}/correct-timestamp", response_model=ComplaintOut)
|
||||
def correct_complaint_timestamp(
|
||||
complaint_id: int,
|
||||
payload: ComplaintCorrectTimestampIn,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(Role.system_admin)),
|
||||
):
|
||||
comp = _load_complaint_or_404(db, complaint_id)
|
||||
now = utc_now()
|
||||
old_val = _norm_utc(getattr(comp, payload.field))
|
||||
new_val = _norm_utc(payload.new_value)
|
||||
|
||||
setattr(comp, payload.field, new_val)
|
||||
comp.updated_by_id = current_user.id
|
||||
|
||||
from_str = old_val.isoformat() if old_val else None
|
||||
to_str = new_val.isoformat() if new_val else None
|
||||
|
||||
db.add(
|
||||
ComplaintEvent(
|
||||
complaint_id=comp.id,
|
||||
event_type="timestamp_corrected",
|
||||
from_value=from_str,
|
||||
to_value=to_str,
|
||||
by_user_id=current_user.id,
|
||||
at=now,
|
||||
note=f"{payload.field}: {payload.reason}",
|
||||
)
|
||||
)
|
||||
log_audit(
|
||||
db,
|
||||
entity_type="complaint",
|
||||
entity_id=comp.id,
|
||||
action="correct_timestamp",
|
||||
changes={"field": payload.field, "from": from_str, "to": to_str, "reason": payload.reason},
|
||||
user_id=current_user.id,
|
||||
)
|
||||
db.commit()
|
||||
return _serialize_one(db, _load_complaint_or_404(db, comp.id))
|
||||
@@ -0,0 +1,455 @@
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
from fastapi import APIRouter, Depends, File, HTTPException, Query, Response, UploadFile, status
|
||||
from fastapi.responses import StreamingResponse
|
||||
from sqlalchemy import or_
|
||||
from sqlalchemy.orm import Session, joinedload
|
||||
|
||||
from ..core.db import get_db
|
||||
from ..core.deps import get_current_user, require_roles
|
||||
from ..core.time_utils import effective_today
|
||||
from ..models import Asset, Contract, PMSchedule, User, Vendor
|
||||
from ..schemas.contracts import (
|
||||
ContractCreate,
|
||||
ContractHistoryOut,
|
||||
ContractListOut,
|
||||
ContractOut,
|
||||
ContractRenewIn,
|
||||
ContractRenewOut,
|
||||
ContractStatusFilter,
|
||||
ContractType,
|
||||
ContractUpdate,
|
||||
)
|
||||
from ..services.attachment_service import get_attachment_counts
|
||||
from ..services.audit import log_audit
|
||||
from ..services.bulk_templates import build_contracts_template_xlsx, process_contracts_import
|
||||
from ..services.calculations import coverage_status
|
||||
from ..services.permissions import Role, maybe_strip_costs_response
|
||||
from ..services.settings_service import get_setting_value
|
||||
|
||||
router = APIRouter(prefix="/contracts", tags=["contracts"])
|
||||
|
||||
|
||||
def _contract_lead_settings(db: Session) -> tuple[int, int]:
|
||||
lead = int(
|
||||
get_setting_value(
|
||||
db,
|
||||
"amc_cmc_lead_days",
|
||||
get_setting_value(db, "contract_expiry_alert_days", 30),
|
||||
)
|
||||
)
|
||||
red = int(
|
||||
get_setting_value(
|
||||
db,
|
||||
"contract_critical_alert_days",
|
||||
get_setting_value(db, "red_threshold_days", 7),
|
||||
)
|
||||
)
|
||||
return lead, red
|
||||
|
||||
|
||||
def _to_contract_out(
|
||||
c: Contract,
|
||||
today: date,
|
||||
lead_days: int,
|
||||
red_days: int,
|
||||
att_counts: dict[int, int],
|
||||
) -> ContractOut:
|
||||
asset = c.asset
|
||||
if c.is_superseded:
|
||||
st, sev = "superseded", "ok"
|
||||
else:
|
||||
st, sev = coverage_status(c.start_date, c.end_date, today, lead_days, red_days)
|
||||
return ContractOut(
|
||||
id=c.id,
|
||||
asset_id=c.asset_id,
|
||||
asset_code=asset.asset_code,
|
||||
asset_name=asset.name,
|
||||
department_id=asset.department_id,
|
||||
department_name=asset.department.name if asset.department else None,
|
||||
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,
|
||||
contract_value=c.contract_value,
|
||||
coverage_period_text=c.coverage_period_text,
|
||||
renewed_from_id=c.renewed_from_id,
|
||||
is_superseded=c.is_superseded,
|
||||
status=st,
|
||||
severity=sev,
|
||||
days_to_expiry=(c.end_date - today).days,
|
||||
attachment_count=att_counts.get(c.id, 0),
|
||||
remarks=c.remarks,
|
||||
created_at=c.created_at,
|
||||
)
|
||||
|
||||
|
||||
def _load_contract(db: Session, contract_id: int) -> Contract | None:
|
||||
return (
|
||||
db.query(Contract)
|
||||
.options(
|
||||
joinedload(Contract.asset).joinedload(Asset.department),
|
||||
joinedload(Contract.provider),
|
||||
)
|
||||
.filter(Contract.id == contract_id)
|
||||
.first()
|
||||
)
|
||||
|
||||
|
||||
@router.get("", response_model=ContractListOut)
|
||||
def list_contracts(
|
||||
q: str = "",
|
||||
department_id: Optional[int] = None,
|
||||
asset_id: Optional[int] = None,
|
||||
provider_id: Optional[int] = None,
|
||||
contract_type: Optional[ContractType] = None,
|
||||
status_filter: Optional[ContractStatusFilter] = Query(None, alias="status"),
|
||||
expiry_from: Optional[date] = None,
|
||||
expiry_to: Optional[date] = None,
|
||||
include_superseded: bool = True,
|
||||
page: int = Query(1, ge=1),
|
||||
page_size: int = Query(200, ge=1, le=500),
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user),
|
||||
):
|
||||
today = effective_today(db)
|
||||
lead_days, red_days = _contract_lead_settings(db)
|
||||
|
||||
query = (
|
||||
db.query(Contract)
|
||||
.join(Asset, Contract.asset_id == Asset.id)
|
||||
.outerjoin(Vendor, Contract.provider_id == Vendor.id)
|
||||
.options(
|
||||
joinedload(Contract.asset).joinedload(Asset.department),
|
||||
joinedload(Contract.provider),
|
||||
)
|
||||
)
|
||||
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 asset_id is not None:
|
||||
query = query.filter(Contract.asset_id == asset_id)
|
||||
if provider_id is not None:
|
||||
query = query.filter(Contract.provider_id == provider_id)
|
||||
if contract_type is not None:
|
||||
query = query.filter(Contract.contract_type == contract_type)
|
||||
if not include_superseded:
|
||||
query = query.filter(Contract.is_superseded.is_(False))
|
||||
if expiry_from is not None:
|
||||
query = query.filter(Contract.end_date >= expiry_from)
|
||||
if expiry_to is not None:
|
||||
query = query.filter(Contract.end_date <= expiry_to)
|
||||
if q and q.strip():
|
||||
like = f"%{q.strip()}%"
|
||||
query = query.filter(
|
||||
or_(
|
||||
Asset.asset_code.ilike(like),
|
||||
Asset.name.ilike(like),
|
||||
Vendor.name.ilike(like),
|
||||
Contract.coverage_period_text.ilike(like),
|
||||
Contract.remarks.ilike(like),
|
||||
)
|
||||
)
|
||||
|
||||
rows = query.order_by(Contract.is_superseded.asc(), Contract.end_date.asc(), Contract.id.desc()).all()
|
||||
att_counts = get_attachment_counts(db, "contract", [r.id for r in rows])
|
||||
items_all = [_to_contract_out(r, today, lead_days, red_days, att_counts) for r in rows]
|
||||
|
||||
if status_filter is not None:
|
||||
items_all = [item for item in items_all if item.status == status_filter]
|
||||
|
||||
total = len(items_all)
|
||||
start = (page - 1) * page_size
|
||||
return maybe_strip_costs_response(
|
||||
ContractListOut(items=items_all[start : start + page_size], total=total),
|
||||
current_user.role,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/history/{asset_id}", response_model=ContractHistoryOut)
|
||||
def get_contract_history(
|
||||
asset_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user),
|
||||
):
|
||||
asset = db.query(Asset).filter(Asset.id == asset_id).first()
|
||||
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)
|
||||
lead_days, red_days = _contract_lead_settings(db)
|
||||
rows = (
|
||||
db.query(Contract)
|
||||
.options(
|
||||
joinedload(Contract.asset).joinedload(Asset.department),
|
||||
joinedload(Contract.provider),
|
||||
)
|
||||
.filter(Contract.asset_id == asset_id)
|
||||
.order_by(Contract.start_date.desc(), Contract.id.desc())
|
||||
.all()
|
||||
)
|
||||
att_counts = get_attachment_counts(db, "contract", [r.id for r in rows])
|
||||
return maybe_strip_costs_response(
|
||||
ContractHistoryOut(
|
||||
items=[_to_contract_out(r, today, lead_days, red_days, att_counts) for r in rows]
|
||||
),
|
||||
current_user.role,
|
||||
)
|
||||
|
||||
|
||||
@router.get("/import-template")
|
||||
def download_contracts_import_template(
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.coordinator)),
|
||||
):
|
||||
buf = build_contracts_template_xlsx(db)
|
||||
return StreamingResponse(
|
||||
buf,
|
||||
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
headers={"Content-Disposition": 'attachment; filename="contracts_import_template.xlsx"'},
|
||||
)
|
||||
|
||||
|
||||
@router.post("/bulk-import")
|
||||
def bulk_import_contracts(
|
||||
file: UploadFile = File(...),
|
||||
dry_run: bool = Query(False),
|
||||
skip_invalid: bool = Query(False),
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.coordinator)),
|
||||
):
|
||||
content = file.file.read()
|
||||
return process_contracts_import(
|
||||
db=db,
|
||||
filename=file.filename or "contracts.xlsx",
|
||||
content=content,
|
||||
user_id=current_user.id,
|
||||
dry_run=dry_run,
|
||||
skip_invalid=skip_invalid,
|
||||
)
|
||||
|
||||
|
||||
@router.post("", response_model=ContractOut, status_code=status.HTTP_201_CREATED)
|
||||
def create_contract(
|
||||
payload: ContractCreate,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.coordinator)),
|
||||
):
|
||||
if payload.end_date < payload.start_date:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="end_date cannot be earlier than start_date.",
|
||||
)
|
||||
if not db.query(Asset.id).filter(Asset.id == payload.asset_id).first():
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Asset not found.")
|
||||
if not db.query(Vendor.id).filter(Vendor.id == payload.provider_id).first():
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Provider vendor not found.")
|
||||
|
||||
existing_contract = (
|
||||
db.query(Contract.id)
|
||||
.filter(
|
||||
Contract.asset_id == payload.asset_id,
|
||||
Contract.contract_type == payload.contract_type,
|
||||
Contract.start_date == payload.start_date,
|
||||
Contract.end_date == payload.end_date,
|
||||
)
|
||||
.first()
|
||||
)
|
||||
if existing_contract:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail="A contract with the same asset, type and dates already exists.",
|
||||
)
|
||||
|
||||
contract = Contract(
|
||||
asset_id=payload.asset_id,
|
||||
contract_type=payload.contract_type,
|
||||
provider_id=payload.provider_id,
|
||||
start_date=payload.start_date,
|
||||
end_date=payload.end_date,
|
||||
contract_value=payload.contract_value,
|
||||
coverage_period_text=payload.coverage_period_text.strip() if payload.coverage_period_text else None,
|
||||
renewed_from_id=None,
|
||||
is_superseded=False,
|
||||
remarks=payload.remarks.strip() if payload.remarks else None,
|
||||
created_by_id=current_user.id,
|
||||
updated_by_id=current_user.id,
|
||||
)
|
||||
db.add(contract)
|
||||
db.flush()
|
||||
|
||||
log_audit(
|
||||
db,
|
||||
entity_type="contract",
|
||||
entity_id=contract.id,
|
||||
action="create",
|
||||
changes={
|
||||
"asset_id": payload.asset_id,
|
||||
"contract_type": payload.contract_type,
|
||||
"provider_id": payload.provider_id,
|
||||
"start_date": str(payload.start_date),
|
||||
"end_date": str(payload.end_date),
|
||||
},
|
||||
user_id=current_user.id,
|
||||
)
|
||||
db.commit()
|
||||
|
||||
loaded = _load_contract(db, contract.id)
|
||||
today = effective_today(db)
|
||||
lead_days, red_days = _contract_lead_settings(db)
|
||||
att_counts = get_attachment_counts(db, "contract", [contract.id])
|
||||
return _to_contract_out(loaded, today, lead_days, red_days, att_counts)
|
||||
|
||||
|
||||
@router.patch("/{contract_id}", response_model=ContractOut)
|
||||
def update_contract(
|
||||
contract_id: int,
|
||||
payload: ContractUpdate,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.coordinator)),
|
||||
):
|
||||
contract = db.query(Contract).filter(Contract.id == contract_id).first()
|
||||
if contract is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Contract not found.")
|
||||
|
||||
data = payload.model_dump(exclude_unset=True)
|
||||
if "provider_id" in data and data["provider_id"] is not None:
|
||||
if not db.query(Vendor.id).filter(Vendor.id == data["provider_id"]).first():
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Provider vendor not found.")
|
||||
|
||||
new_start = data.get("start_date", contract.start_date)
|
||||
new_end = data.get("end_date", contract.end_date)
|
||||
if new_end < new_start:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="end_date cannot be earlier than start_date.",
|
||||
)
|
||||
|
||||
changes: dict[str, dict[str, object]] = {}
|
||||
for k, v in data.items():
|
||||
if isinstance(v, str):
|
||||
v = v.strip() or None
|
||||
old_val = getattr(contract, k)
|
||||
if old_val != v:
|
||||
changes[k] = {"from": old_val, "to": v}
|
||||
setattr(contract, k, v)
|
||||
contract.updated_by_id = current_user.id
|
||||
|
||||
if changes:
|
||||
log_audit(
|
||||
db,
|
||||
entity_type="contract",
|
||||
entity_id=contract.id,
|
||||
action="update",
|
||||
changes=changes,
|
||||
user_id=current_user.id,
|
||||
)
|
||||
db.commit()
|
||||
|
||||
loaded = _load_contract(db, contract.id)
|
||||
today = effective_today(db)
|
||||
lead_days, red_days = _contract_lead_settings(db)
|
||||
att_counts = get_attachment_counts(db, "contract", [contract.id])
|
||||
return _to_contract_out(loaded, today, lead_days, red_days, att_counts)
|
||||
|
||||
|
||||
@router.delete("/{contract_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
def delete_contract(
|
||||
contract_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.coordinator)),
|
||||
):
|
||||
contract = db.query(Contract).filter(Contract.id == contract_id).first()
|
||||
if contract is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Contract not found.")
|
||||
|
||||
db.query(Contract).filter(Contract.renewed_from_id == contract.id).update({"renewed_from_id": None})
|
||||
db.query(PMSchedule).filter(PMSchedule.contract_id == contract.id).update({"contract_id": None})
|
||||
|
||||
log_audit(
|
||||
db,
|
||||
entity_type="contract",
|
||||
entity_id=contract.id,
|
||||
action="delete",
|
||||
changes={"asset_id": contract.asset_id, "contract_type": contract.contract_type},
|
||||
user_id=current_user.id,
|
||||
)
|
||||
db.delete(contract)
|
||||
db.commit()
|
||||
return Response(status_code=status.HTTP_204_NO_CONTENT)
|
||||
|
||||
|
||||
@router.post("/{contract_id}/renew", response_model=ContractRenewOut)
|
||||
def renew_contract(
|
||||
contract_id: int,
|
||||
payload: ContractRenewIn,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.coordinator)),
|
||||
):
|
||||
old_contract = db.query(Contract).filter(Contract.id == contract_id).first()
|
||||
if old_contract is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Contract not found.")
|
||||
|
||||
if payload.end_date < payload.start_date:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="end_date cannot be earlier than start_date.",
|
||||
)
|
||||
|
||||
target_provider_id = payload.provider_id if payload.provider_id is not None else old_contract.provider_id
|
||||
if not db.query(Vendor.id).filter(Vendor.id == target_provider_id).first():
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Provider vendor not found.")
|
||||
|
||||
old_contract.is_superseded = True
|
||||
old_contract.updated_by_id = current_user.id
|
||||
|
||||
new_contract = Contract(
|
||||
asset_id=old_contract.asset_id,
|
||||
contract_type=payload.contract_type or old_contract.contract_type,
|
||||
provider_id=target_provider_id,
|
||||
start_date=payload.start_date,
|
||||
end_date=payload.end_date,
|
||||
contract_value=payload.contract_value if payload.contract_value is not None else old_contract.contract_value,
|
||||
coverage_period_text=(
|
||||
payload.coverage_period_text.strip()
|
||||
if payload.coverage_period_text is not None
|
||||
else old_contract.coverage_period_text
|
||||
),
|
||||
renewed_from_id=old_contract.id,
|
||||
is_superseded=False,
|
||||
remarks=payload.remarks.strip() if payload.remarks else None,
|
||||
created_by_id=current_user.id,
|
||||
updated_by_id=current_user.id,
|
||||
)
|
||||
db.add(new_contract)
|
||||
db.flush()
|
||||
|
||||
log_audit(
|
||||
db,
|
||||
entity_type="contract",
|
||||
entity_id=old_contract.id,
|
||||
action="renew",
|
||||
changes={
|
||||
"superseded_contract_id": old_contract.id,
|
||||
"new_contract_id": new_contract.id,
|
||||
"start_date": str(payload.start_date),
|
||||
"end_date": str(payload.end_date),
|
||||
},
|
||||
user_id=current_user.id,
|
||||
)
|
||||
db.commit()
|
||||
|
||||
today = effective_today(db)
|
||||
lead_days, red_days = _contract_lead_settings(db)
|
||||
att_counts = get_attachment_counts(db, "contract", [old_contract.id, new_contract.id])
|
||||
loaded_old = _load_contract(db, old_contract.id)
|
||||
loaded_new = _load_contract(db, new_contract.id)
|
||||
return ContractRenewOut(
|
||||
old_contract=_to_contract_out(loaded_old, today, lead_days, red_days, att_counts),
|
||||
new_contract=_to_contract_out(loaded_new, today, lead_days, red_days, att_counts),
|
||||
)
|
||||
@@ -0,0 +1,336 @@
|
||||
from datetime import date
|
||||
from fastapi import APIRouter, Depends
|
||||
from sqlalchemy.orm import Session, joinedload
|
||||
|
||||
from ..core.db import get_db
|
||||
from ..core.deps import get_current_user
|
||||
from ..core.time_utils import add_months, effective_now_utc, effective_today
|
||||
from ..models import (
|
||||
Asset,
|
||||
CalibrationRecord,
|
||||
Complaint,
|
||||
Contract,
|
||||
DemoEquipment,
|
||||
Department,
|
||||
PMRecord,
|
||||
User,
|
||||
)
|
||||
from ..schemas.dashboard import (
|
||||
ComplaintsByDepartmentItem,
|
||||
ComplaintsByStatusItem,
|
||||
DashboardKPIs,
|
||||
DashboardSummaryOut,
|
||||
MonthlyDowntimeItem,
|
||||
MonthlyPMComparisonItem,
|
||||
NeedsAttentionItem,
|
||||
RecentComplaintItem,
|
||||
)
|
||||
from ..services.alerts import get_visible_notifications_for_user, notification_link_url
|
||||
from ..services.calculations import (
|
||||
clip_downtime_to_month,
|
||||
compute_downtime_minutes,
|
||||
compute_schedule_status,
|
||||
coverage_status,
|
||||
)
|
||||
from ..services.permissions import Role
|
||||
from ..services.scoping import resolve_department_scope
|
||||
from ..services.settings_service import get_setting_value
|
||||
|
||||
router = APIRouter(prefix="/dashboard", tags=["dashboard"])
|
||||
|
||||
|
||||
@router.get("/summary", response_model=DashboardSummaryOut)
|
||||
def get_dashboard_summary(
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user),
|
||||
):
|
||||
today = effective_today(db)
|
||||
eff_now = effective_now_utc(db)
|
||||
|
||||
scope = resolve_department_scope(current_user)
|
||||
if scope.is_empty:
|
||||
cur_month_start = date(today.year, today.month, 1)
|
||||
months_seq = [add_months(cur_month_start, offset) for offset in range(-5, 1)]
|
||||
return DashboardSummaryOut(
|
||||
department_scope="Unassigned Department",
|
||||
effective_today=today,
|
||||
kpis=DashboardKPIs(
|
||||
total_assets=0,
|
||||
assets_under_repair=0,
|
||||
open_complaints=0,
|
||||
pm_due_this_month=0,
|
||||
calibrations_due=0,
|
||||
contracts_expiring=0,
|
||||
equipment_on_demo=0,
|
||||
),
|
||||
complaints_by_status=[
|
||||
ComplaintsByStatusItem(status="open", count=0),
|
||||
ComplaintsByStatusItem(status="in_progress", count=0),
|
||||
ComplaintsByStatusItem(status="closed", count=0),
|
||||
],
|
||||
complaints_by_department=[],
|
||||
monthly_downtime_trend=[
|
||||
MonthlyDowntimeItem(
|
||||
month=f"{m.year:04d}-{m.month:02d}",
|
||||
label=m.strftime("%b %Y"),
|
||||
downtime_minutes=0,
|
||||
downtime_hours=0.0,
|
||||
)
|
||||
for m in months_seq
|
||||
],
|
||||
pm_planned_vs_completed=[
|
||||
MonthlyPMComparisonItem(
|
||||
month=f"{m.year:04d}-{m.month:02d}",
|
||||
label=m.strftime("%b %Y"),
|
||||
planned=0,
|
||||
completed=0,
|
||||
)
|
||||
for m in months_seq
|
||||
],
|
||||
needs_attention=[],
|
||||
recent_complaints=[],
|
||||
)
|
||||
|
||||
scoped_dept_id: int | None = scope.department_id
|
||||
dept_scope_name: str | None = None
|
||||
if scoped_dept_id is not None:
|
||||
dept_obj = db.query(Department).filter(Department.id == scoped_dept_id).first()
|
||||
dept_scope_name = dept_obj.name if dept_obj else None
|
||||
|
||||
# Settings for dynamic calculations
|
||||
cal_lead = int(
|
||||
get_setting_value(
|
||||
db,
|
||||
"calibration_due_window_days",
|
||||
get_setting_value(db, "calibration_lead_days", 15),
|
||||
)
|
||||
)
|
||||
amc_lead = int(
|
||||
get_setting_value(
|
||||
db,
|
||||
"amc_cmc_lead_days",
|
||||
get_setting_value(db, "contract_expiry_alert_days", 30),
|
||||
)
|
||||
)
|
||||
red_days = int(get_setting_value(db, "red_threshold_days", 7))
|
||||
downtime_milestone = str(get_setting_value(db, "downtime_end_milestone", "restored_at"))
|
||||
|
||||
# 1. Assets KPIs
|
||||
asset_q = db.query(Asset)
|
||||
if scoped_dept_id is not None:
|
||||
asset_q = asset_q.filter(Asset.department_id == scoped_dept_id)
|
||||
total_assets = asset_q.count()
|
||||
assets_under_repair = asset_q.filter(Asset.status == "under_repair").count()
|
||||
|
||||
# 2. Complaints queries (used for KPIs, status chart, dept chart, downtime trend, recent list)
|
||||
cmp_q = (
|
||||
db.query(Complaint)
|
||||
.join(Asset, Complaint.asset_id == Asset.id)
|
||||
.options(joinedload(Complaint.asset).joinedload(Asset.department))
|
||||
)
|
||||
if scoped_dept_id is not None:
|
||||
cmp_q = cmp_q.filter(Asset.department_id == scoped_dept_id)
|
||||
complaints = cmp_q.order_by(Complaint.registered_at.desc(), Complaint.id.desc()).all()
|
||||
|
||||
open_cnt = sum(1 for c in complaints if c.call_status == "open")
|
||||
in_prog_cnt = sum(1 for c in complaints if c.call_status == "in_progress")
|
||||
closed_cnt = sum(1 for c in complaints if c.call_status == "closed")
|
||||
open_complaints_kpi = open_cnt + in_prog_cnt
|
||||
|
||||
complaints_by_status = [
|
||||
ComplaintsByStatusItem(status="open", count=open_cnt),
|
||||
ComplaintsByStatusItem(status="in_progress", count=in_prog_cnt),
|
||||
ComplaintsByStatusItem(status="closed", count=closed_cnt),
|
||||
]
|
||||
|
||||
dept_q = db.query(Department).filter(Department.is_active.is_(True))
|
||||
if scoped_dept_id is not None:
|
||||
dept_q = dept_q.filter(Department.id == scoped_dept_id)
|
||||
departments = dept_q.order_by(Department.name.asc()).all()
|
||||
dept_crit_counts: dict[str, dict[str, int]] = {
|
||||
d.name: {"critical": 0, "non_critical": 0} for d in departments
|
||||
}
|
||||
for c in complaints:
|
||||
dname = c.asset.department.name if (c.asset and c.asset.department) else "Unknown"
|
||||
if dname not in dept_crit_counts:
|
||||
dept_crit_counts[dname] = {"critical": 0, "non_critical": 0}
|
||||
if c.priority == "critical":
|
||||
dept_crit_counts[dname]["critical"] += 1
|
||||
else:
|
||||
dept_crit_counts[dname]["non_critical"] += 1
|
||||
|
||||
complaints_by_department = [
|
||||
ComplaintsByDepartmentItem(
|
||||
department=dname,
|
||||
critical=vals["critical"],
|
||||
non_critical=vals["non_critical"],
|
||||
)
|
||||
for dname, vals in dept_crit_counts.items()
|
||||
]
|
||||
|
||||
# 3. PM records (KPI + 6-month chart)
|
||||
pm_q = db.query(PMRecord).join(Asset, PMRecord.asset_id == Asset.id)
|
||||
if scoped_dept_id is not None:
|
||||
pm_q = pm_q.filter(Asset.department_id == scoped_dept_id)
|
||||
pm_records = pm_q.all()
|
||||
|
||||
pm_due_this_month = 0
|
||||
for r in pm_records:
|
||||
if r.status in ("completed", "rescheduled"):
|
||||
continue
|
||||
if r.planned_date < today or (
|
||||
r.planned_date.year == today.year and r.planned_date.month == today.month
|
||||
):
|
||||
pm_due_this_month += 1
|
||||
|
||||
# 4. Calibrations due KPI
|
||||
cal_q = db.query(CalibrationRecord).join(Asset, CalibrationRecord.asset_id == Asset.id)
|
||||
if scoped_dept_id is not None:
|
||||
cal_q = cal_q.filter(Asset.department_id == scoped_dept_id)
|
||||
cal_records = cal_q.all()
|
||||
|
||||
calibrations_due = 0
|
||||
for r in cal_records:
|
||||
st, _ = compute_schedule_status(r.due_date, r.status, today, cal_lead, red_days)
|
||||
if st in ("due", "overdue"):
|
||||
calibrations_due += 1
|
||||
|
||||
# 5. Contracts expiring KPI
|
||||
con_q = (
|
||||
db.query(Contract)
|
||||
.join(Asset, Contract.asset_id == Asset.id)
|
||||
.filter(Contract.is_superseded.is_(False))
|
||||
)
|
||||
if scoped_dept_id is not None:
|
||||
con_q = con_q.filter(Asset.department_id == scoped_dept_id)
|
||||
contracts = con_q.all()
|
||||
|
||||
contracts_expiring = 0
|
||||
for c in contracts:
|
||||
st, _ = coverage_status(c.start_date, c.end_date, today, amc_lead, red_days)
|
||||
if st in ("expiring", "expired"):
|
||||
contracts_expiring += 1
|
||||
|
||||
# 6. Equipment on demo KPI
|
||||
demo_q = db.query(DemoEquipment).filter(DemoEquipment.actual_return_date.is_(None))
|
||||
if scoped_dept_id is not None:
|
||||
demo_q = demo_q.filter(DemoEquipment.department_id == scoped_dept_id)
|
||||
equipment_on_demo = demo_q.count()
|
||||
|
||||
# 7. Last 6 calendar months (oldest -> current month)
|
||||
cur_month_start = date(today.year, today.month, 1)
|
||||
months_seq = [add_months(cur_month_start, offset) for offset in range(-5, 1)]
|
||||
|
||||
monthly_downtime_trend: list[MonthlyDowntimeItem] = []
|
||||
pm_planned_vs_completed: list[MonthlyPMComparisonItem] = []
|
||||
|
||||
for m_start in months_seq:
|
||||
y, m = m_start.year, m_start.month
|
||||
m_key = f"{y:04d}-{m:02d}"
|
||||
m_label = m_start.strftime("%b %Y")
|
||||
|
||||
total_mins = 0
|
||||
for c in complaints:
|
||||
end_map = {
|
||||
"attended_at": c.attended_at,
|
||||
"restored_at": c.restored_at,
|
||||
"closed_at": c.closed_at,
|
||||
}
|
||||
end_dt = end_map.get(downtime_milestone) or eff_now
|
||||
mins, _ = clip_downtime_to_month(c.registered_at, end_dt, y, m)
|
||||
total_mins += mins
|
||||
|
||||
monthly_downtime_trend.append(
|
||||
MonthlyDowntimeItem(
|
||||
month=m_key,
|
||||
label=m_label,
|
||||
downtime_minutes=total_mins,
|
||||
downtime_hours=round(total_mins / 60.0, 2),
|
||||
)
|
||||
)
|
||||
|
||||
planned_cnt = sum(
|
||||
1 for r in pm_records if r.planned_date.year == y and r.planned_date.month == m
|
||||
)
|
||||
completed_cnt = sum(
|
||||
1
|
||||
for r in pm_records
|
||||
if r.status == "completed"
|
||||
and (r.completed_date or r.planned_date).year == y
|
||||
and (r.completed_date or r.planned_date).month == m
|
||||
)
|
||||
pm_planned_vs_completed.append(
|
||||
MonthlyPMComparisonItem(
|
||||
month=m_key,
|
||||
label=m_label,
|
||||
planned=planned_cnt,
|
||||
completed=completed_cnt,
|
||||
)
|
||||
)
|
||||
|
||||
# 8. Needs attention (top 15 unread red notifications visible to user)
|
||||
visible_notifs, read_map = get_visible_notifications_for_user(db, current_user)
|
||||
red_unread = [
|
||||
n for n in visible_notifs if n.severity == "red" and n.id not in read_map
|
||||
]
|
||||
red_unread.sort(key=lambda n: (n.due_date or today, -n.id))
|
||||
needs_attention = [
|
||||
NeedsAttentionItem(
|
||||
id=n.id,
|
||||
type=n.type,
|
||||
severity=n.severity,
|
||||
title=n.title,
|
||||
message=n.message,
|
||||
entity_type=n.entity_type,
|
||||
entity_id=n.entity_id,
|
||||
due_date=n.due_date,
|
||||
link_url=notification_link_url(n.entity_type, n.entity_id),
|
||||
)
|
||||
for n in red_unread[:15]
|
||||
]
|
||||
|
||||
# 9. Recent complaints (latest 8)
|
||||
recent_complaints: list[RecentComplaintItem] = []
|
||||
for c in complaints[:8]:
|
||||
dt_mins, is_ongoing = compute_downtime_minutes(
|
||||
c.registered_at,
|
||||
c.attended_at,
|
||||
c.restored_at,
|
||||
c.closed_at,
|
||||
milestone=downtime_milestone,
|
||||
now_utc=eff_now,
|
||||
)
|
||||
recent_complaints.append(
|
||||
RecentComplaintItem(
|
||||
id=c.id,
|
||||
complaint_no=c.complaint_no,
|
||||
asset_code=c.asset.asset_code,
|
||||
asset_name=c.asset.name,
|
||||
department_name=c.asset.department.name if c.asset.department else None,
|
||||
priority=c.priority,
|
||||
call_status=c.call_status,
|
||||
registered_at=c.registered_at,
|
||||
downtime_minutes=dt_mins,
|
||||
downtime_is_ongoing=is_ongoing,
|
||||
)
|
||||
)
|
||||
|
||||
return DashboardSummaryOut(
|
||||
department_scope=dept_scope_name,
|
||||
effective_today=today,
|
||||
kpis=DashboardKPIs(
|
||||
total_assets=total_assets,
|
||||
assets_under_repair=assets_under_repair,
|
||||
open_complaints=open_complaints_kpi,
|
||||
pm_due_this_month=pm_due_this_month,
|
||||
calibrations_due=calibrations_due,
|
||||
contracts_expiring=contracts_expiring,
|
||||
equipment_on_demo=equipment_on_demo,
|
||||
),
|
||||
complaints_by_status=complaints_by_status,
|
||||
complaints_by_department=complaints_by_department,
|
||||
monthly_downtime_trend=monthly_downtime_trend,
|
||||
pm_planned_vs_completed=pm_planned_vs_completed,
|
||||
needs_attention=needs_attention,
|
||||
recent_complaints=recent_complaints,
|
||||
)
|
||||
@@ -0,0 +1,325 @@
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Response, status
|
||||
from sqlalchemy import or_
|
||||
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
|
||||
from ..models import DemoEquipment, Department, Location, User, Vendor
|
||||
from ..schemas.demo_equipment import (
|
||||
DemoEquipmentCreate,
|
||||
DemoEquipmentListOut,
|
||||
DemoEquipmentOut,
|
||||
DemoEquipmentReturnIn,
|
||||
DemoEquipmentUpdate,
|
||||
DemoStatusFilter,
|
||||
)
|
||||
from ..services.attachment_service import get_attachment_counts
|
||||
from ..services.audit import log_audit
|
||||
from ..services.permissions import Role
|
||||
from ..services.settings_service import get_setting_value
|
||||
|
||||
router = APIRouter(prefix="/demo-equipment", tags=["demo_equipment"])
|
||||
|
||||
|
||||
def _to_demo_out(
|
||||
item: DemoEquipment,
|
||||
today: date,
|
||||
alert_days: int,
|
||||
att_counts: dict[int, int],
|
||||
) -> DemoEquipmentOut:
|
||||
if item.actual_return_date is not None:
|
||||
st = "returned"
|
||||
sev = "ok"
|
||||
days_rem = (item.expected_return_date - item.actual_return_date).days
|
||||
elif item.expected_return_date < today:
|
||||
st = "overdue_return"
|
||||
sev = "red"
|
||||
days_rem = (item.expected_return_date - today).days
|
||||
else:
|
||||
st = "on_demo"
|
||||
days_rem = (item.expected_return_date - today).days
|
||||
sev = "yellow" if days_rem <= alert_days else "info"
|
||||
|
||||
return DemoEquipmentOut(
|
||||
id=item.id,
|
||||
name=item.name,
|
||||
equipment_type=item.equipment_type,
|
||||
serial_no=item.serial_no,
|
||||
supplier_id=item.supplier_id,
|
||||
supplier_name=item.supplier.name if item.supplier else None,
|
||||
department_id=item.department_id,
|
||||
department_name=item.department.name if item.department else None,
|
||||
location_id=item.location_id,
|
||||
location_name=item.location.name if item.location else None,
|
||||
start_date=item.start_date,
|
||||
expected_return_date=item.expected_return_date,
|
||||
actual_return_date=item.actual_return_date,
|
||||
status=st,
|
||||
severity=sev,
|
||||
days_remaining=days_rem,
|
||||
attachment_count=att_counts.get(item.id, 0),
|
||||
remarks=item.remarks,
|
||||
created_at=item.created_at,
|
||||
)
|
||||
|
||||
|
||||
def _load_demo(db: Session, demo_id: int) -> DemoEquipment | None:
|
||||
return (
|
||||
db.query(DemoEquipment)
|
||||
.options(
|
||||
joinedload(DemoEquipment.supplier),
|
||||
joinedload(DemoEquipment.department),
|
||||
joinedload(DemoEquipment.location),
|
||||
)
|
||||
.filter(DemoEquipment.id == demo_id)
|
||||
.first()
|
||||
)
|
||||
|
||||
|
||||
@router.get("", response_model=DemoEquipmentListOut)
|
||||
def list_demo_equipment(
|
||||
q: str = "",
|
||||
supplier_id: Optional[int] = None,
|
||||
department_id: Optional[int] = None,
|
||||
status_filter: Optional[DemoStatusFilter] = Query(None, alias="status"),
|
||||
date_from: Optional[date] = None,
|
||||
date_to: Optional[date] = None,
|
||||
page: int = Query(1, ge=1),
|
||||
page_size: int = Query(200, ge=1, le=500),
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user),
|
||||
):
|
||||
today = effective_today(db)
|
||||
alert_days = int(get_setting_value(db, "demo_return_alert_days", 3))
|
||||
|
||||
query = (
|
||||
db.query(DemoEquipment)
|
||||
.outerjoin(Vendor, DemoEquipment.supplier_id == Vendor.id)
|
||||
.options(
|
||||
joinedload(DemoEquipment.supplier),
|
||||
joinedload(DemoEquipment.department),
|
||||
joinedload(DemoEquipment.location),
|
||||
)
|
||||
)
|
||||
if current_user.role == Role.department_user.value:
|
||||
query = query.filter(DemoEquipment.department_id == current_user.department_id)
|
||||
elif department_id is not None:
|
||||
query = query.filter(DemoEquipment.department_id == department_id)
|
||||
|
||||
if supplier_id is not None:
|
||||
query = query.filter(DemoEquipment.supplier_id == supplier_id)
|
||||
if date_from is not None:
|
||||
query = query.filter(DemoEquipment.expected_return_date >= date_from)
|
||||
if date_to is not None:
|
||||
query = query.filter(DemoEquipment.expected_return_date <= date_to)
|
||||
if q and q.strip():
|
||||
like = f"%{q.strip()}%"
|
||||
query = query.filter(
|
||||
or_(
|
||||
DemoEquipment.name.ilike(like),
|
||||
DemoEquipment.equipment_type.ilike(like),
|
||||
Vendor.name.ilike(like),
|
||||
DemoEquipment.remarks.ilike(like),
|
||||
)
|
||||
)
|
||||
|
||||
rows = query.order_by(DemoEquipment.expected_return_date.asc(), DemoEquipment.id.desc()).all()
|
||||
att_counts = get_attachment_counts(db, "demo_equipment", [r.id for r in rows])
|
||||
items_all = [_to_demo_out(r, today, alert_days, att_counts) for r in rows]
|
||||
|
||||
if status_filter is not None:
|
||||
items_all = [item for item in items_all if item.status == status_filter]
|
||||
|
||||
total = len(items_all)
|
||||
start = (page - 1) * page_size
|
||||
return DemoEquipmentListOut(items=items_all[start : start + page_size], total=total)
|
||||
|
||||
|
||||
@router.post("", response_model=DemoEquipmentOut, status_code=status.HTTP_201_CREATED)
|
||||
def create_demo_equipment(
|
||||
payload: DemoEquipmentCreate,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.coordinator)),
|
||||
):
|
||||
if payload.expected_return_date < payload.start_date:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="expected_return_date cannot be earlier than start_date.",
|
||||
)
|
||||
if not db.query(Vendor.id).filter(Vendor.id == payload.supplier_id).first():
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Supplier vendor not found.")
|
||||
if not db.query(Department.id).filter(Department.id == payload.department_id).first():
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Department not found.")
|
||||
if payload.location_id is not None:
|
||||
if not db.query(Location.id).filter(Location.id == payload.location_id).first():
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Location not found.")
|
||||
|
||||
item = DemoEquipment(
|
||||
name=payload.name.strip(),
|
||||
equipment_type=payload.equipment_type.strip(),
|
||||
serial_no=payload.serial_no.strip() if payload.serial_no else None,
|
||||
supplier_id=payload.supplier_id,
|
||||
department_id=payload.department_id,
|
||||
location_id=payload.location_id,
|
||||
start_date=payload.start_date,
|
||||
expected_return_date=payload.expected_return_date,
|
||||
actual_return_date=None,
|
||||
remarks=payload.remarks.strip() if payload.remarks else None,
|
||||
created_by_id=current_user.id,
|
||||
updated_by_id=current_user.id,
|
||||
)
|
||||
db.add(item)
|
||||
db.flush()
|
||||
|
||||
log_audit(
|
||||
db,
|
||||
entity_type="demo_equipment",
|
||||
entity_id=item.id,
|
||||
action="create",
|
||||
changes={
|
||||
"name": item.name,
|
||||
"supplier_id": payload.supplier_id,
|
||||
"department_id": payload.department_id,
|
||||
"expected_return_date": str(payload.expected_return_date),
|
||||
},
|
||||
user_id=current_user.id,
|
||||
)
|
||||
db.commit()
|
||||
|
||||
loaded = _load_demo(db, item.id)
|
||||
today = effective_today(db)
|
||||
alert_days = int(get_setting_value(db, "demo_return_alert_days", 3))
|
||||
att_counts = get_attachment_counts(db, "demo_equipment", [item.id])
|
||||
return _to_demo_out(loaded, today, alert_days, att_counts)
|
||||
|
||||
|
||||
@router.patch("/{demo_id}", response_model=DemoEquipmentOut)
|
||||
def update_demo_equipment(
|
||||
demo_id: int,
|
||||
payload: DemoEquipmentUpdate,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.coordinator)),
|
||||
):
|
||||
item = db.query(DemoEquipment).filter(DemoEquipment.id == demo_id).first()
|
||||
if item is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Demo equipment not found.")
|
||||
|
||||
data = payload.model_dump(exclude_unset=True)
|
||||
if "supplier_id" in data and data["supplier_id"] is not None:
|
||||
if not db.query(Vendor.id).filter(Vendor.id == data["supplier_id"]).first():
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Supplier vendor not found.")
|
||||
if "department_id" in data and data["department_id"] is not None:
|
||||
if not db.query(Department.id).filter(Department.id == data["department_id"]).first():
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Department not found.")
|
||||
if "location_id" in data and data["location_id"] is not None:
|
||||
if not db.query(Location.id).filter(Location.id == data["location_id"]).first():
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Location not found.")
|
||||
|
||||
new_start = data.get("start_date", item.start_date)
|
||||
new_exp = data.get("expected_return_date", item.expected_return_date)
|
||||
if new_exp < new_start:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="expected_return_date cannot be earlier than start_date.",
|
||||
)
|
||||
|
||||
changes: dict[str, dict[str, object]] = {}
|
||||
for k, v in data.items():
|
||||
if k in ("name", "equipment_type") and isinstance(v, str):
|
||||
v = v.strip()
|
||||
if not v:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail=f"{k} cannot be blank.",
|
||||
)
|
||||
elif k == "remarks" and isinstance(v, str):
|
||||
v = v.strip() or None
|
||||
old_val = getattr(item, k)
|
||||
if old_val != v:
|
||||
changes[k] = {"from": old_val, "to": v}
|
||||
setattr(item, k, v)
|
||||
item.updated_by_id = current_user.id
|
||||
|
||||
if changes:
|
||||
log_audit(
|
||||
db,
|
||||
entity_type="demo_equipment",
|
||||
entity_id=item.id,
|
||||
action="update",
|
||||
changes=changes,
|
||||
user_id=current_user.id,
|
||||
)
|
||||
db.commit()
|
||||
|
||||
loaded = _load_demo(db, item.id)
|
||||
today = effective_today(db)
|
||||
alert_days = int(get_setting_value(db, "demo_return_alert_days", 3))
|
||||
att_counts = get_attachment_counts(db, "demo_equipment", [item.id])
|
||||
return _to_demo_out(loaded, today, alert_days, att_counts)
|
||||
|
||||
|
||||
@router.delete("/{demo_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
def delete_demo_equipment(
|
||||
demo_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.coordinator)),
|
||||
):
|
||||
item = db.query(DemoEquipment).filter(DemoEquipment.id == demo_id).first()
|
||||
if item is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Demo equipment not found.")
|
||||
|
||||
log_audit(
|
||||
db,
|
||||
entity_type="demo_equipment",
|
||||
entity_id=item.id,
|
||||
action="delete",
|
||||
changes={"name": item.name},
|
||||
user_id=current_user.id,
|
||||
)
|
||||
db.delete(item)
|
||||
db.commit()
|
||||
return Response(status_code=status.HTTP_204_NO_CONTENT)
|
||||
|
||||
|
||||
@router.post("/{demo_id}/return", response_model=DemoEquipmentOut)
|
||||
def return_demo_equipment(
|
||||
demo_id: int,
|
||||
payload: DemoEquipmentReturnIn,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.coordinator)),
|
||||
):
|
||||
item = db.query(DemoEquipment).filter(DemoEquipment.id == demo_id).first()
|
||||
if item is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Demo equipment not found.")
|
||||
|
||||
if item.actual_return_date is not None:
|
||||
raise CodedHTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Demo equipment has already been marked as returned.",
|
||||
code="ALREADY_RETURNED",
|
||||
)
|
||||
|
||||
item.actual_return_date = payload.actual_return_date
|
||||
if payload.remarks and payload.remarks.strip():
|
||||
item.remarks = payload.remarks.strip()
|
||||
item.updated_by_id = current_user.id
|
||||
|
||||
log_audit(
|
||||
db,
|
||||
entity_type="demo_equipment",
|
||||
entity_id=item.id,
|
||||
action="return",
|
||||
changes={"actual_return_date": str(payload.actual_return_date)},
|
||||
user_id=current_user.id,
|
||||
)
|
||||
db.commit()
|
||||
|
||||
loaded = _load_demo(db, item.id)
|
||||
today = effective_today(db)
|
||||
alert_days = int(get_setting_value(db, "demo_return_alert_days", 3))
|
||||
att_counts = get_attachment_counts(db, "demo_equipment", [item.id])
|
||||
return _to_demo_out(loaded, today, alert_days, att_counts)
|
||||
@@ -0,0 +1,8 @@
|
||||
from fastapi import APIRouter
|
||||
|
||||
router = APIRouter(tags=["health"])
|
||||
|
||||
|
||||
@router.get("/health")
|
||||
def health_check():
|
||||
return {"status": "ok", "service": "Poona Hospital AMS", "version": "0.1.0"}
|
||||
@@ -0,0 +1,332 @@
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
from fastapi import APIRouter, Depends, File, HTTPException, Query, Response, UploadFile, status
|
||||
from fastapi.responses import StreamingResponse
|
||||
from sqlalchemy import func, or_
|
||||
from sqlalchemy.orm import Session, joinedload
|
||||
|
||||
from ..core.db import get_db
|
||||
from ..core.deps import get_current_user, require_roles
|
||||
from ..core.time_utils import effective_today
|
||||
from ..models import Asset, InsurancePolicy, User, Vendor
|
||||
from ..schemas.insurance import (
|
||||
InsuranceCreate,
|
||||
InsuranceListOut,
|
||||
InsuranceOut,
|
||||
InsuranceStatusFilter,
|
||||
InsuranceUpdate,
|
||||
)
|
||||
from ..services.attachment_service import get_attachment_counts
|
||||
from ..services.audit import log_audit
|
||||
from ..services.bulk_templates import build_insurance_template_xlsx, process_insurance_import
|
||||
from ..services.calculations import coverage_status
|
||||
from ..services.permissions import Role
|
||||
from ..services.settings_service import get_setting_value
|
||||
|
||||
router = APIRouter(prefix="/insurance", tags=["insurance"])
|
||||
|
||||
|
||||
def _insurance_lead_settings(db: Session) -> tuple[int, int]:
|
||||
lead = int(
|
||||
get_setting_value(
|
||||
db,
|
||||
"insurance_lead_days",
|
||||
get_setting_value(db, "insurance_expiry_alert_days", 30),
|
||||
)
|
||||
)
|
||||
red = int(get_setting_value(db, "red_threshold_days", 7))
|
||||
return lead, red
|
||||
|
||||
|
||||
def _to_insurance_out(
|
||||
pol: InsurancePolicy,
|
||||
today: date,
|
||||
lead_days: int,
|
||||
red_days: int,
|
||||
att_counts: dict[int, int],
|
||||
) -> InsuranceOut:
|
||||
asset = pol.asset
|
||||
st, sev = coverage_status(pol.start_date, pol.end_date, today, lead_days, red_days)
|
||||
return InsuranceOut(
|
||||
id=pol.id,
|
||||
asset_id=pol.asset_id,
|
||||
asset_code=asset.asset_code,
|
||||
asset_name=asset.name,
|
||||
department_id=asset.department_id,
|
||||
department_name=asset.department.name if asset.department else None,
|
||||
insurer_id=pol.insurer_id,
|
||||
insurer_name=pol.insurer.name if pol.insurer else None,
|
||||
policy_no=pol.policy_no,
|
||||
start_date=pol.start_date,
|
||||
end_date=pol.end_date,
|
||||
coverage_amount=pol.coverage_amount,
|
||||
status=st,
|
||||
severity=sev,
|
||||
days_to_expiry=(pol.end_date - today).days,
|
||||
attachment_count=att_counts.get(pol.id, 0),
|
||||
remarks=pol.remarks,
|
||||
created_at=pol.created_at,
|
||||
)
|
||||
|
||||
|
||||
def _load_insurance(db: Session, policy_id: int) -> InsurancePolicy | None:
|
||||
return (
|
||||
db.query(InsurancePolicy)
|
||||
.options(
|
||||
joinedload(InsurancePolicy.asset).joinedload(Asset.department),
|
||||
joinedload(InsurancePolicy.insurer),
|
||||
)
|
||||
.filter(InsurancePolicy.id == policy_id)
|
||||
.first()
|
||||
)
|
||||
|
||||
|
||||
@router.get("", response_model=InsuranceListOut)
|
||||
def list_insurance_policies(
|
||||
q: str = "",
|
||||
department_id: Optional[int] = None,
|
||||
asset_id: Optional[int] = None,
|
||||
insurer_id: Optional[int] = None,
|
||||
status_filter: Optional[InsuranceStatusFilter] = Query(None, alias="status"),
|
||||
expiry_from: Optional[date] = None,
|
||||
expiry_to: Optional[date] = None,
|
||||
page: int = Query(1, ge=1),
|
||||
page_size: int = Query(200, ge=1, le=500),
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user),
|
||||
):
|
||||
today = effective_today(db)
|
||||
lead_days, red_days = _insurance_lead_settings(db)
|
||||
|
||||
query = (
|
||||
db.query(InsurancePolicy)
|
||||
.join(Asset, InsurancePolicy.asset_id == Asset.id)
|
||||
.outerjoin(Vendor, InsurancePolicy.insurer_id == Vendor.id)
|
||||
.options(
|
||||
joinedload(InsurancePolicy.asset).joinedload(Asset.department),
|
||||
joinedload(InsurancePolicy.insurer),
|
||||
)
|
||||
)
|
||||
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 asset_id is not None:
|
||||
query = query.filter(InsurancePolicy.asset_id == asset_id)
|
||||
if insurer_id is not None:
|
||||
query = query.filter(InsurancePolicy.insurer_id == insurer_id)
|
||||
if expiry_from is not None:
|
||||
query = query.filter(InsurancePolicy.end_date >= expiry_from)
|
||||
if expiry_to is not None:
|
||||
query = query.filter(InsurancePolicy.end_date <= expiry_to)
|
||||
if q and q.strip():
|
||||
like = f"%{q.strip()}%"
|
||||
query = query.filter(
|
||||
or_(
|
||||
Asset.asset_code.ilike(like),
|
||||
Asset.name.ilike(like),
|
||||
Vendor.name.ilike(like),
|
||||
InsurancePolicy.policy_no.ilike(like),
|
||||
InsurancePolicy.remarks.ilike(like),
|
||||
)
|
||||
)
|
||||
|
||||
rows = query.order_by(InsurancePolicy.end_date.asc(), InsurancePolicy.id.desc()).all()
|
||||
att_counts = get_attachment_counts(db, "insurance", [r.id for r in rows])
|
||||
items_all = [_to_insurance_out(r, today, lead_days, red_days, att_counts) for r in rows]
|
||||
|
||||
if status_filter is not None:
|
||||
items_all = [item for item in items_all if item.status == status_filter]
|
||||
|
||||
total = len(items_all)
|
||||
start = (page - 1) * page_size
|
||||
return InsuranceListOut(items=items_all[start : start + page_size], total=total)
|
||||
|
||||
|
||||
@router.get("/import-template")
|
||||
def download_insurance_import_template(
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.coordinator)),
|
||||
):
|
||||
buf = build_insurance_template_xlsx(db)
|
||||
return StreamingResponse(
|
||||
buf,
|
||||
media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
|
||||
headers={"Content-Disposition": 'attachment; filename="insurance_import_template.xlsx"'},
|
||||
)
|
||||
|
||||
|
||||
@router.post("/bulk-import")
|
||||
def bulk_import_insurance(
|
||||
file: UploadFile = File(...),
|
||||
dry_run: bool = Query(False),
|
||||
skip_invalid: bool = Query(False),
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.coordinator)),
|
||||
):
|
||||
content = file.file.read()
|
||||
return process_insurance_import(
|
||||
db=db,
|
||||
filename=file.filename or "insurance.xlsx",
|
||||
content=content,
|
||||
user_id=current_user.id,
|
||||
dry_run=dry_run,
|
||||
skip_invalid=skip_invalid,
|
||||
)
|
||||
|
||||
|
||||
@router.post("", response_model=InsuranceOut, status_code=status.HTTP_201_CREATED)
|
||||
def create_insurance_policy(
|
||||
payload: InsuranceCreate,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.coordinator)),
|
||||
):
|
||||
if payload.end_date < payload.start_date:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="end_date cannot be earlier than start_date.",
|
||||
)
|
||||
asset = db.query(Asset).filter(Asset.id == payload.asset_id).first()
|
||||
if asset is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Asset not found.")
|
||||
if not db.query(Vendor.id).filter(Vendor.id == payload.insurer_id).first():
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Insurer vendor not found.")
|
||||
|
||||
clean_policy_no = payload.policy_no.strip()
|
||||
if not clean_policy_no:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="policy_no cannot be blank.",
|
||||
)
|
||||
|
||||
existing_policy = (
|
||||
db.query(InsurancePolicy.id)
|
||||
.filter(func.lower(func.trim(InsurancePolicy.policy_no)) == clean_policy_no.lower())
|
||||
.first()
|
||||
)
|
||||
if existing_policy:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail="Policy number already exists.",
|
||||
)
|
||||
|
||||
asset.insurance_applicable = True
|
||||
pol = InsurancePolicy(
|
||||
asset_id=payload.asset_id,
|
||||
insurer_id=payload.insurer_id,
|
||||
policy_no=clean_policy_no,
|
||||
start_date=payload.start_date,
|
||||
end_date=payload.end_date,
|
||||
coverage_amount=payload.coverage_amount,
|
||||
remarks=payload.remarks.strip() if payload.remarks else None,
|
||||
created_by_id=current_user.id,
|
||||
updated_by_id=current_user.id,
|
||||
)
|
||||
db.add(pol)
|
||||
db.flush()
|
||||
|
||||
log_audit(
|
||||
db,
|
||||
entity_type="insurance",
|
||||
entity_id=pol.id,
|
||||
action="create",
|
||||
changes={
|
||||
"asset_id": payload.asset_id,
|
||||
"insurer_id": payload.insurer_id,
|
||||
"policy_no": clean_policy_no,
|
||||
"start_date": str(payload.start_date),
|
||||
"end_date": str(payload.end_date),
|
||||
},
|
||||
user_id=current_user.id,
|
||||
)
|
||||
db.commit()
|
||||
|
||||
loaded = _load_insurance(db, pol.id)
|
||||
today = effective_today(db)
|
||||
lead_days, red_days = _insurance_lead_settings(db)
|
||||
att_counts = get_attachment_counts(db, "insurance", [pol.id])
|
||||
return _to_insurance_out(loaded, today, lead_days, red_days, att_counts)
|
||||
|
||||
|
||||
@router.patch("/{policy_id}", response_model=InsuranceOut)
|
||||
def update_insurance_policy(
|
||||
policy_id: int,
|
||||
payload: InsuranceUpdate,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.coordinator)),
|
||||
):
|
||||
pol = db.query(InsurancePolicy).filter(InsurancePolicy.id == policy_id).first()
|
||||
if pol is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Insurance policy not found.")
|
||||
|
||||
data = payload.model_dump(exclude_unset=True)
|
||||
if "insurer_id" in data and data["insurer_id"] is not None:
|
||||
if not db.query(Vendor.id).filter(Vendor.id == data["insurer_id"]).first():
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Insurer vendor not found.")
|
||||
if "policy_no" in data and data["policy_no"] is not None:
|
||||
clean_no = data["policy_no"].strip()
|
||||
if not clean_no:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="policy_no cannot be blank.",
|
||||
)
|
||||
data["policy_no"] = clean_no
|
||||
|
||||
new_start = data.get("start_date", pol.start_date)
|
||||
new_end = data.get("end_date", pol.end_date)
|
||||
if new_end < new_start:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="end_date cannot be earlier than start_date.",
|
||||
)
|
||||
|
||||
changes: dict[str, dict[str, object]] = {}
|
||||
for k, v in data.items():
|
||||
if k == "remarks" and isinstance(v, str):
|
||||
v = v.strip() or None
|
||||
old_val = getattr(pol, k)
|
||||
if old_val != v:
|
||||
changes[k] = {"from": old_val, "to": v}
|
||||
setattr(pol, k, v)
|
||||
pol.updated_by_id = current_user.id
|
||||
|
||||
if changes:
|
||||
log_audit(
|
||||
db,
|
||||
entity_type="insurance",
|
||||
entity_id=pol.id,
|
||||
action="update",
|
||||
changes=changes,
|
||||
user_id=current_user.id,
|
||||
)
|
||||
db.commit()
|
||||
|
||||
loaded = _load_insurance(db, pol.id)
|
||||
today = effective_today(db)
|
||||
lead_days, red_days = _insurance_lead_settings(db)
|
||||
att_counts = get_attachment_counts(db, "insurance", [pol.id])
|
||||
return _to_insurance_out(loaded, today, lead_days, red_days, att_counts)
|
||||
|
||||
|
||||
@router.delete("/{policy_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
def delete_insurance_policy(
|
||||
policy_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.coordinator)),
|
||||
):
|
||||
pol = db.query(InsurancePolicy).filter(InsurancePolicy.id == policy_id).first()
|
||||
if pol is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Insurance policy not found.")
|
||||
|
||||
log_audit(
|
||||
db,
|
||||
entity_type="insurance",
|
||||
entity_id=pol.id,
|
||||
action="delete",
|
||||
changes={"asset_id": pol.asset_id, "policy_no": pol.policy_no},
|
||||
user_id=current_user.id,
|
||||
)
|
||||
db.delete(pol)
|
||||
db.commit()
|
||||
return Response(status_code=status.HTTP_204_NO_CONTENT)
|
||||
@@ -0,0 +1,393 @@
|
||||
from typing import 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 ..models.masters import Category, Department, Location, User, Vendor
|
||||
from ..schemas.masters import (
|
||||
CategoryCreate,
|
||||
CategoryOut,
|
||||
CategoryUpdate,
|
||||
DepartmentCreate,
|
||||
DepartmentOut,
|
||||
DepartmentUpdate,
|
||||
LocationCreate,
|
||||
LocationOut,
|
||||
LocationUpdate,
|
||||
PaginatedOut,
|
||||
VendorCreate,
|
||||
VendorOut,
|
||||
VendorUpdate,
|
||||
)
|
||||
from ..services.permissions import Role
|
||||
|
||||
router = APIRouter(tags=["masters"])
|
||||
|
||||
|
||||
def _paginate(query, page: int, page_size: int):
|
||||
total = query.count()
|
||||
if page_size > 0:
|
||||
query = query.offset((page - 1) * page_size).limit(page_size)
|
||||
return query.all(), total
|
||||
|
||||
|
||||
def _loc_out(loc: Location) -> LocationOut:
|
||||
return LocationOut(
|
||||
id=loc.id,
|
||||
department_id=loc.department_id,
|
||||
department_name=loc.department.name if loc.department else None,
|
||||
name=loc.name,
|
||||
floor_wing=loc.floor_wing,
|
||||
is_active=loc.is_active,
|
||||
)
|
||||
|
||||
|
||||
# ---------------- Departments ----------------
|
||||
@router.get("/departments", response_model=PaginatedOut[DepartmentOut])
|
||||
def list_departments(
|
||||
q: Optional[str] = None,
|
||||
page: int = Query(1, ge=1),
|
||||
page_size: int = Query(100, ge=0, le=500),
|
||||
include_inactive: bool = False,
|
||||
db: Session = Depends(get_db),
|
||||
_: User = Depends(get_current_user),
|
||||
):
|
||||
query = db.query(Department)
|
||||
if not include_inactive:
|
||||
query = query.filter(Department.is_active.is_(True))
|
||||
if q and q.strip():
|
||||
like = f"%{q.strip()}%"
|
||||
query = query.filter(or_(Department.name.ilike(like), Department.code.ilike(like)))
|
||||
query = query.order_by(Department.name.asc())
|
||||
items, total = _paginate(query, page, page_size)
|
||||
return {"items": items, "total": total}
|
||||
|
||||
|
||||
@router.post("/departments", response_model=DepartmentOut, status_code=status.HTTP_201_CREATED)
|
||||
def create_department(
|
||||
payload: DepartmentCreate,
|
||||
db: Session = Depends(get_db),
|
||||
_: User = Depends(require_roles(Role.system_admin)),
|
||||
):
|
||||
dept = Department(
|
||||
name=payload.name.strip(),
|
||||
code=payload.code.strip().upper(),
|
||||
description=payload.description,
|
||||
is_active=payload.is_active,
|
||||
)
|
||||
db.add(dept)
|
||||
try:
|
||||
db.commit()
|
||||
except IntegrityError:
|
||||
db.rollback()
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail="Department with this name or code already exists.",
|
||||
)
|
||||
db.refresh(dept)
|
||||
return dept
|
||||
|
||||
|
||||
@router.patch("/departments/{dept_id}", response_model=DepartmentOut)
|
||||
def update_department(
|
||||
dept_id: int,
|
||||
payload: DepartmentUpdate,
|
||||
db: Session = Depends(get_db),
|
||||
_: User = Depends(require_roles(Role.system_admin)),
|
||||
):
|
||||
dept = db.query(Department).filter(Department.id == dept_id).first()
|
||||
if dept is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Department not found.")
|
||||
data = payload.model_dump(exclude_unset=True)
|
||||
if "name" in data and data["name"] is not None:
|
||||
data["name"] = data["name"].strip()
|
||||
if "code" in data and data["code"] is not None:
|
||||
data["code"] = data["code"].strip().upper()
|
||||
for k, v in data.items():
|
||||
setattr(dept, k, v)
|
||||
try:
|
||||
db.commit()
|
||||
except IntegrityError:
|
||||
db.rollback()
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail="Department with this name or code already exists.",
|
||||
)
|
||||
db.refresh(dept)
|
||||
return dept
|
||||
|
||||
|
||||
@router.delete("/departments/{dept_id}", response_model=DepartmentOut)
|
||||
def delete_department(
|
||||
dept_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
_: User = Depends(require_roles(Role.system_admin)),
|
||||
):
|
||||
dept = db.query(Department).filter(Department.id == dept_id).first()
|
||||
if dept is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Department not found.")
|
||||
dept.is_active = False
|
||||
db.commit()
|
||||
db.refresh(dept)
|
||||
return dept
|
||||
|
||||
|
||||
# ---------------- Locations ----------------
|
||||
@router.get("/locations", response_model=PaginatedOut[LocationOut])
|
||||
def list_locations(
|
||||
q: Optional[str] = None,
|
||||
department_id: Optional[int] = None,
|
||||
page: int = Query(1, ge=1),
|
||||
page_size: int = Query(100, ge=0, le=500),
|
||||
include_inactive: bool = False,
|
||||
db: Session = Depends(get_db),
|
||||
_: User = Depends(get_current_user),
|
||||
):
|
||||
query = db.query(Location).options(joinedload(Location.department))
|
||||
if not include_inactive:
|
||||
query = query.filter(Location.is_active.is_(True))
|
||||
if department_id is not None:
|
||||
query = query.filter(Location.department_id == department_id)
|
||||
if q and q.strip():
|
||||
like = f"%{q.strip()}%"
|
||||
query = query.filter(or_(Location.name.ilike(like), Location.floor_wing.ilike(like)))
|
||||
query = query.order_by(Location.name.asc())
|
||||
items, total = _paginate(query, page, page_size)
|
||||
return {"items": [_loc_out(loc) for loc in items], "total": total}
|
||||
|
||||
|
||||
@router.post("/locations", response_model=LocationOut, status_code=status.HTTP_201_CREATED)
|
||||
def create_location(
|
||||
payload: LocationCreate,
|
||||
db: Session = Depends(get_db),
|
||||
_: User = Depends(require_roles(Role.system_admin)),
|
||||
):
|
||||
dept = db.query(Department).filter(Department.id == payload.department_id).first()
|
||||
if dept is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Department not found.")
|
||||
loc = Location(
|
||||
department_id=payload.department_id,
|
||||
name=payload.name.strip(),
|
||||
floor_wing=payload.floor_wing,
|
||||
is_active=payload.is_active,
|
||||
)
|
||||
db.add(loc)
|
||||
db.commit()
|
||||
db.refresh(loc)
|
||||
loc.department = dept
|
||||
return _loc_out(loc)
|
||||
|
||||
|
||||
@router.patch("/locations/{location_id}", response_model=LocationOut)
|
||||
def update_location(
|
||||
location_id: int,
|
||||
payload: LocationUpdate,
|
||||
db: Session = Depends(get_db),
|
||||
_: User = Depends(require_roles(Role.system_admin)),
|
||||
):
|
||||
loc = db.query(Location).options(joinedload(Location.department)).filter(Location.id == location_id).first()
|
||||
if loc is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Location not found.")
|
||||
data = payload.model_dump(exclude_unset=True)
|
||||
if "department_id" in data and data["department_id"] is not None:
|
||||
dept = db.query(Department).filter(Department.id == data["department_id"]).first()
|
||||
if dept is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Department not found.")
|
||||
if "name" in data and data["name"] is not None:
|
||||
data["name"] = data["name"].strip()
|
||||
for k, v in data.items():
|
||||
setattr(loc, k, v)
|
||||
db.commit()
|
||||
db.refresh(loc)
|
||||
return _loc_out(loc)
|
||||
|
||||
|
||||
@router.delete("/locations/{location_id}", response_model=LocationOut)
|
||||
def delete_location(
|
||||
location_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
_: User = Depends(require_roles(Role.system_admin)),
|
||||
):
|
||||
loc = db.query(Location).options(joinedload(Location.department)).filter(Location.id == location_id).first()
|
||||
if loc is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Location not found.")
|
||||
loc.is_active = False
|
||||
db.commit()
|
||||
db.refresh(loc)
|
||||
return _loc_out(loc)
|
||||
|
||||
|
||||
# ---------------- Categories ----------------
|
||||
@router.get("/categories", response_model=PaginatedOut[CategoryOut])
|
||||
def list_categories(
|
||||
q: Optional[str] = None,
|
||||
page: int = Query(1, ge=1),
|
||||
page_size: int = Query(100, ge=0, le=500),
|
||||
include_inactive: bool = False,
|
||||
db: Session = Depends(get_db),
|
||||
_: User = Depends(get_current_user),
|
||||
):
|
||||
query = db.query(Category)
|
||||
if not include_inactive:
|
||||
query = query.filter(Category.is_active.is_(True))
|
||||
if q and q.strip():
|
||||
like = f"%{q.strip()}%"
|
||||
query = query.filter(Category.name.ilike(like))
|
||||
query = query.order_by(Category.name.asc())
|
||||
items, total = _paginate(query, page, page_size)
|
||||
return {"items": items, "total": total}
|
||||
|
||||
|
||||
@router.post("/categories", response_model=CategoryOut, status_code=status.HTTP_201_CREATED)
|
||||
def create_category(
|
||||
payload: CategoryCreate,
|
||||
db: Session = Depends(get_db),
|
||||
_: User = Depends(require_roles(Role.system_admin)),
|
||||
):
|
||||
cat = Category(
|
||||
name=payload.name.strip(),
|
||||
description=payload.description,
|
||||
default_useful_life_years=payload.default_useful_life_years,
|
||||
is_active=payload.is_active,
|
||||
)
|
||||
db.add(cat)
|
||||
try:
|
||||
db.commit()
|
||||
except IntegrityError:
|
||||
db.rollback()
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail="Category with this name already exists.",
|
||||
)
|
||||
db.refresh(cat)
|
||||
return cat
|
||||
|
||||
|
||||
@router.patch("/categories/{category_id}", response_model=CategoryOut)
|
||||
def update_category(
|
||||
category_id: int,
|
||||
payload: CategoryUpdate,
|
||||
db: Session = Depends(get_db),
|
||||
_: User = Depends(require_roles(Role.system_admin)),
|
||||
):
|
||||
cat = db.query(Category).filter(Category.id == category_id).first()
|
||||
if cat is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Category not found.")
|
||||
data = payload.model_dump(exclude_unset=True)
|
||||
if "name" in data and data["name"] is not None:
|
||||
data["name"] = data["name"].strip()
|
||||
for k, v in data.items():
|
||||
setattr(cat, k, v)
|
||||
try:
|
||||
db.commit()
|
||||
except IntegrityError:
|
||||
db.rollback()
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail="Category with this name already exists.",
|
||||
)
|
||||
db.refresh(cat)
|
||||
return cat
|
||||
|
||||
|
||||
@router.delete("/categories/{category_id}", response_model=CategoryOut)
|
||||
def delete_category(
|
||||
category_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
_: User = Depends(require_roles(Role.system_admin)),
|
||||
):
|
||||
cat = db.query(Category).filter(Category.id == category_id).first()
|
||||
if cat is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Category not found.")
|
||||
cat.is_active = False
|
||||
db.commit()
|
||||
db.refresh(cat)
|
||||
return cat
|
||||
|
||||
|
||||
# ---------------- Vendors ----------------
|
||||
@router.get("/vendors", response_model=PaginatedOut[VendorOut])
|
||||
def list_vendors(
|
||||
q: Optional[str] = None,
|
||||
vendor_type: Optional[str] = None,
|
||||
page: int = Query(1, ge=1),
|
||||
page_size: int = Query(100, ge=0, le=500),
|
||||
include_inactive: bool = False,
|
||||
db: Session = Depends(get_db),
|
||||
_: User = Depends(get_current_user),
|
||||
):
|
||||
query = db.query(Vendor)
|
||||
if not include_inactive:
|
||||
query = query.filter(Vendor.is_active.is_(True))
|
||||
if vendor_type:
|
||||
query = query.filter(Vendor.vendor_type == vendor_type)
|
||||
if q and q.strip():
|
||||
like = f"%{q.strip()}%"
|
||||
query = query.filter(
|
||||
or_(
|
||||
Vendor.name.ilike(like),
|
||||
Vendor.contact_person.ilike(like),
|
||||
Vendor.email.ilike(like),
|
||||
)
|
||||
)
|
||||
query = query.order_by(Vendor.name.asc())
|
||||
items, total = _paginate(query, page, page_size)
|
||||
return {"items": items, "total": total}
|
||||
|
||||
|
||||
@router.post("/vendors", response_model=VendorOut, status_code=status.HTTP_201_CREATED)
|
||||
def create_vendor(
|
||||
payload: VendorCreate,
|
||||
db: Session = Depends(get_db),
|
||||
_: User = Depends(require_roles(Role.system_admin)),
|
||||
):
|
||||
vendor = Vendor(
|
||||
name=payload.name.strip(),
|
||||
vendor_type=payload.vendor_type,
|
||||
contact_person=payload.contact_person,
|
||||
phone=payload.phone,
|
||||
email=payload.email,
|
||||
address=payload.address,
|
||||
is_active=payload.is_active,
|
||||
)
|
||||
db.add(vendor)
|
||||
db.commit()
|
||||
db.refresh(vendor)
|
||||
return vendor
|
||||
|
||||
|
||||
@router.patch("/vendors/{vendor_id}", response_model=VendorOut)
|
||||
def update_vendor(
|
||||
vendor_id: int,
|
||||
payload: VendorUpdate,
|
||||
db: Session = Depends(get_db),
|
||||
_: User = Depends(require_roles(Role.system_admin)),
|
||||
):
|
||||
vendor = db.query(Vendor).filter(Vendor.id == vendor_id).first()
|
||||
if vendor is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Vendor not found.")
|
||||
data = payload.model_dump(exclude_unset=True)
|
||||
if "name" in data and data["name"] is not None:
|
||||
data["name"] = data["name"].strip()
|
||||
for k, v in data.items():
|
||||
setattr(vendor, k, v)
|
||||
db.commit()
|
||||
db.refresh(vendor)
|
||||
return vendor
|
||||
|
||||
|
||||
@router.delete("/vendors/{vendor_id}", response_model=VendorOut)
|
||||
def delete_vendor(
|
||||
vendor_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
_: User = Depends(require_roles(Role.system_admin)),
|
||||
):
|
||||
vendor = db.query(Vendor).filter(Vendor.id == vendor_id).first()
|
||||
if vendor is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Vendor not found.")
|
||||
vendor.is_active = False
|
||||
db.commit()
|
||||
db.refresh(vendor)
|
||||
return vendor
|
||||
@@ -0,0 +1,150 @@
|
||||
from typing import Optional
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..core.db import get_db
|
||||
from ..core.deps import get_current_user, require_roles
|
||||
from ..core.time_utils import utc_now
|
||||
from ..models import Notification, NotificationRead, User
|
||||
from ..schemas.notifications import (
|
||||
AlertRunOut,
|
||||
NotificationListOut,
|
||||
NotificationOut,
|
||||
NotificationReadAllOut,
|
||||
NotificationReadOut,
|
||||
)
|
||||
from ..services.alerts import (
|
||||
get_visible_notifications_for_user,
|
||||
notification_link_url,
|
||||
run_alert_check,
|
||||
)
|
||||
from ..services.permissions import Role
|
||||
|
||||
router = APIRouter(tags=["notifications"])
|
||||
|
||||
|
||||
@router.post("/alerts/run", response_model=AlertRunOut)
|
||||
def trigger_alert_run(
|
||||
db: Session = Depends(get_db),
|
||||
_: User = Depends(require_roles(Role.system_admin)),
|
||||
):
|
||||
result = run_alert_check(db)
|
||||
db.commit()
|
||||
return AlertRunOut(**result)
|
||||
|
||||
|
||||
@router.get("/notifications", response_model=NotificationListOut)
|
||||
def list_notifications(
|
||||
notif_type: Optional[str] = Query(None, alias="type"),
|
||||
severity: Optional[str] = None,
|
||||
unread_only: bool = False,
|
||||
limit: Optional[int] = Query(None, ge=1, le=200),
|
||||
page: int = Query(1, ge=1),
|
||||
page_size: int = Query(50, ge=1, le=200),
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user),
|
||||
):
|
||||
visible, read_map = get_visible_notifications_for_user(db, current_user)
|
||||
|
||||
unread_count = sum(1 for n in visible if n.id not in read_map)
|
||||
unread_calibration_count = sum(
|
||||
1 for n in visible if n.id not in read_map and n.type == "calibration_due"
|
||||
)
|
||||
|
||||
filtered: list[Notification] = []
|
||||
for n in visible:
|
||||
is_read = n.id in read_map
|
||||
if notif_type and n.type != notif_type:
|
||||
continue
|
||||
if severity and n.severity != severity:
|
||||
continue
|
||||
if unread_only and is_read:
|
||||
continue
|
||||
filtered.append(n)
|
||||
|
||||
total = len(filtered)
|
||||
eff_size = limit if limit is not None else page_size
|
||||
start = (page - 1) * eff_size
|
||||
page_items = filtered[start : start + eff_size]
|
||||
|
||||
items_out = [
|
||||
NotificationOut(
|
||||
id=n.id,
|
||||
type=n.type,
|
||||
severity=n.severity,
|
||||
title=n.title,
|
||||
message=n.message,
|
||||
entity_type=n.entity_type,
|
||||
entity_id=n.entity_id,
|
||||
due_date=n.due_date,
|
||||
link_url=notification_link_url(n.entity_type, n.entity_id),
|
||||
is_read=n.id in read_map,
|
||||
read_at=read_map.get(n.id),
|
||||
created_at=n.created_at,
|
||||
)
|
||||
for n in page_items
|
||||
]
|
||||
|
||||
return NotificationListOut(
|
||||
items=items_out,
|
||||
total=total,
|
||||
unread_count=unread_count,
|
||||
unread_calibration_count=unread_calibration_count,
|
||||
)
|
||||
|
||||
|
||||
@router.post("/notifications/read-all", response_model=NotificationReadAllOut)
|
||||
def mark_all_notifications_read(
|
||||
notif_type: Optional[str] = Query(None, alias="type"),
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user),
|
||||
):
|
||||
visible, read_map = get_visible_notifications_for_user(db, current_user)
|
||||
now = utc_now()
|
||||
marked = 0
|
||||
for n in visible:
|
||||
if n.id in read_map:
|
||||
continue
|
||||
if notif_type and n.type != notif_type:
|
||||
continue
|
||||
db.add(
|
||||
NotificationRead(
|
||||
notification_id=n.id,
|
||||
user_id=current_user.id,
|
||||
read_at=now,
|
||||
)
|
||||
)
|
||||
marked += 1
|
||||
if marked:
|
||||
db.commit()
|
||||
return NotificationReadAllOut(marked_read=marked)
|
||||
|
||||
|
||||
@router.post("/notifications/{notification_id}/read", response_model=NotificationReadOut)
|
||||
def mark_notification_read(
|
||||
notification_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user),
|
||||
):
|
||||
notif = db.query(Notification).filter(Notification.id == notification_id).first()
|
||||
if notif is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Notification not found.")
|
||||
|
||||
visible, read_map = get_visible_notifications_for_user(db, current_user)
|
||||
if all(n.id != notification_id for n in visible):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Access denied for this notification.",
|
||||
)
|
||||
|
||||
if notification_id not in read_map:
|
||||
db.add(
|
||||
NotificationRead(
|
||||
notification_id=notification_id,
|
||||
user_id=current_user.id,
|
||||
read_at=utc_now(),
|
||||
)
|
||||
)
|
||||
db.commit()
|
||||
|
||||
return NotificationReadOut(notification_id=notification_id, is_read=True)
|
||||
@@ -0,0 +1,680 @@
|
||||
from datetime import date
|
||||
import re
|
||||
from typing import Optional
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
||||
from sqlalchemy import or_
|
||||
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 add_months, effective_today, format_date
|
||||
from ..models import Asset, Contract, PMRecord, PMSchedule, User, Vendor
|
||||
from ..schemas.assets import CoverageOut
|
||||
from ..schemas.pm import (
|
||||
PMRecordCompleteIn,
|
||||
PMRecordCompleteOut,
|
||||
PMRecordListOut,
|
||||
PMRecordOut,
|
||||
PMRecordRescheduleIn,
|
||||
PMRecordRescheduleOut,
|
||||
PMRecordStatusFilter,
|
||||
PMRecordSummaryCounts,
|
||||
PMScheduleCreate,
|
||||
PMScheduleListOut,
|
||||
PMScheduleOut,
|
||||
PMScheduleUpdate,
|
||||
PMServiceMode,
|
||||
)
|
||||
from ..services.audit import log_audit
|
||||
from ..services.calculations import compute_schedule_status
|
||||
from ..services.coverage import get_active_amc_cmc, get_coverage, get_coverage_map
|
||||
from ..services.permissions import Role, maybe_strip_costs_response
|
||||
from ..services.settings_service import get_setting_value
|
||||
|
||||
router = APIRouter(prefix="/pm", tags=["pm"])
|
||||
|
||||
_MONTH_RE = re.compile(r"^(\d{4})-(0[1-9]|1[0-2])$")
|
||||
|
||||
|
||||
def _pm_lead_settings(db: Session) -> dict[str, int]:
|
||||
return {
|
||||
"in_house": int(get_setting_value(db, "pm_inhouse_lead_days", 15)),
|
||||
"outsourced": int(get_setting_value(db, "pm_outsourced_lead_days", 15)),
|
||||
"red": int(get_setting_value(db, "red_threshold_days", 7)),
|
||||
}
|
||||
|
||||
|
||||
def _to_schedule_out(
|
||||
s: PMSchedule,
|
||||
cov: dict | None = None,
|
||||
no_active_contract: bool | None = None,
|
||||
) -> PMScheduleOut:
|
||||
asset = s.asset
|
||||
contract_summary = None
|
||||
if s.contract is not None:
|
||||
contract_summary = f"{s.contract.contract_type} (till {format_date(s.contract.end_date)})"
|
||||
cov_out = CoverageOut(**cov) if cov is not None else None
|
||||
return PMScheduleOut(
|
||||
id=s.id,
|
||||
asset_id=s.asset_id,
|
||||
asset_code=asset.asset_code,
|
||||
asset_name=asset.name,
|
||||
department_id=asset.department_id,
|
||||
department_name=asset.department.name if asset.department else None,
|
||||
location_name=asset.location.name if asset.location else None,
|
||||
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,
|
||||
contract_summary=contract_summary,
|
||||
cost_per_visit=s.cost_per_visit,
|
||||
coverage_tag=cov_out.tag if cov_out else None,
|
||||
coverage=cov_out,
|
||||
no_active_contract=no_active_contract,
|
||||
next_planned_date=s.next_planned_date,
|
||||
is_active=s.is_active,
|
||||
created_at=s.created_at,
|
||||
)
|
||||
|
||||
|
||||
def _to_record_out(
|
||||
rec: PMRecord,
|
||||
today: date,
|
||||
leads: dict[str, int],
|
||||
cov: dict | None = None,
|
||||
) -> PMRecordOut:
|
||||
sched = rec.schedule
|
||||
asset = rec.asset
|
||||
mode = sched.service_mode
|
||||
lead_days = leads["in_house"] if mode == "in_house" else leads["outsourced"]
|
||||
if rec.status in ("completed", "rescheduled"):
|
||||
comp_status, severity = rec.status, "ok"
|
||||
else:
|
||||
comp_status, severity = compute_schedule_status(
|
||||
rec.planned_date, None, today, lead_days, leads["red"]
|
||||
)
|
||||
cov_out = CoverageOut(**cov) if cov is not None else None
|
||||
return PMRecordOut(
|
||||
id=rec.id,
|
||||
schedule_id=rec.schedule_id,
|
||||
asset_id=rec.asset_id,
|
||||
asset_code=asset.asset_code,
|
||||
asset_name=asset.name,
|
||||
department_id=asset.department_id,
|
||||
department_name=asset.department.name if asset.department else None,
|
||||
location_name=asset.location.name if asset.location else None,
|
||||
service_mode=mode,
|
||||
responsible_team=sched.responsible_team,
|
||||
provider_id=sched.provider_id,
|
||||
provider_name=sched.provider.name if sched.provider else None,
|
||||
contract_id=sched.contract_id,
|
||||
planned_date=rec.planned_date,
|
||||
completed_date=rec.completed_date,
|
||||
status=comp_status,
|
||||
severity=severity,
|
||||
service_details=rec.service_details,
|
||||
remarks=rec.remarks,
|
||||
rescheduled_to=rec.rescheduled_to,
|
||||
frequency_months=sched.frequency_months,
|
||||
coverage_tag=cov_out.tag if cov_out else None,
|
||||
coverage=cov_out,
|
||||
)
|
||||
|
||||
|
||||
def _load_schedule_with_joins(db: Session, schedule_id: int) -> PMSchedule | None:
|
||||
return (
|
||||
db.query(PMSchedule)
|
||||
.options(
|
||||
joinedload(PMSchedule.asset).joinedload(Asset.department),
|
||||
joinedload(PMSchedule.asset).joinedload(Asset.location),
|
||||
joinedload(PMSchedule.provider),
|
||||
joinedload(PMSchedule.contract),
|
||||
)
|
||||
.filter(PMSchedule.id == schedule_id)
|
||||
.first()
|
||||
)
|
||||
|
||||
|
||||
def _load_record_with_joins(db: Session, record_id: int) -> PMRecord | None:
|
||||
return (
|
||||
db.query(PMRecord)
|
||||
.options(
|
||||
joinedload(PMRecord.asset).joinedload(Asset.department),
|
||||
joinedload(PMRecord.asset).joinedload(Asset.location),
|
||||
joinedload(PMRecord.schedule).joinedload(PMSchedule.provider),
|
||||
)
|
||||
.filter(PMRecord.id == record_id)
|
||||
.first()
|
||||
)
|
||||
|
||||
|
||||
def _validate_schedule_fields(
|
||||
db: Session,
|
||||
*,
|
||||
asset_id: int,
|
||||
service_mode: str,
|
||||
responsible_team: Optional[str],
|
||||
provider_id: Optional[int],
|
||||
contract_id: Optional[int],
|
||||
allow_auto_fill: bool = False,
|
||||
) -> tuple[Optional[str], Optional[int], Optional[int], bool]:
|
||||
if service_mode == "in_house":
|
||||
clean_team = responsible_team.strip() if responsible_team else ""
|
||||
if not clean_team:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="responsible_team is required for in_house PM schedules.",
|
||||
)
|
||||
return clean_team, None, None, False
|
||||
|
||||
no_active_contract = False
|
||||
if allow_auto_fill and (provider_id is None or contract_id is None):
|
||||
active_contract = get_active_amc_cmc(db, asset_id, effective_today(db))
|
||||
if active_contract is not None:
|
||||
if contract_id is None:
|
||||
contract_id = active_contract.id
|
||||
if provider_id is None:
|
||||
provider_id = active_contract.provider_id
|
||||
elif provider_id is None and contract_id is None:
|
||||
no_active_contract = True
|
||||
|
||||
if provider_id is not None:
|
||||
provider = db.query(Vendor.id).filter(Vendor.id == provider_id).first()
|
||||
if provider is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Service provider vendor not found.")
|
||||
elif not allow_auto_fill:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="provider_id is required for outsourced PM schedules.",
|
||||
)
|
||||
|
||||
if contract_id is not None:
|
||||
contract = db.query(Contract).filter(Contract.id == contract_id).first()
|
||||
if contract is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Contract not found.")
|
||||
if contract.asset_id != asset_id:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="Contract does not belong to the selected asset.",
|
||||
)
|
||||
clean_team = responsible_team.strip() if responsible_team and responsible_team.strip() else None
|
||||
return clean_team, provider_id, contract_id, no_active_contract
|
||||
|
||||
|
||||
@router.get("/schedules", response_model=PMScheduleListOut)
|
||||
def list_pm_schedules(
|
||||
q: str = "",
|
||||
department_id: Optional[int] = None,
|
||||
asset_id: Optional[int] = None,
|
||||
service_mode: Optional[PMServiceMode] = None,
|
||||
is_active: Optional[bool] = None,
|
||||
page: int = Query(1, ge=1),
|
||||
page_size: int = Query(200, ge=1, le=500),
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user),
|
||||
):
|
||||
query = (
|
||||
db.query(PMSchedule)
|
||||
.join(Asset, PMSchedule.asset_id == Asset.id)
|
||||
.outerjoin(Vendor, PMSchedule.provider_id == Vendor.id)
|
||||
.options(
|
||||
joinedload(PMSchedule.asset).joinedload(Asset.department),
|
||||
joinedload(PMSchedule.asset).joinedload(Asset.location),
|
||||
joinedload(PMSchedule.provider),
|
||||
joinedload(PMSchedule.contract),
|
||||
)
|
||||
)
|
||||
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 asset_id is not None:
|
||||
query = query.filter(PMSchedule.asset_id == asset_id)
|
||||
if service_mode is not None:
|
||||
query = query.filter(PMSchedule.service_mode == service_mode)
|
||||
if is_active is not None:
|
||||
query = query.filter(PMSchedule.is_active.is_(is_active))
|
||||
if q and q.strip():
|
||||
like = f"%{q.strip()}%"
|
||||
query = query.filter(
|
||||
or_(
|
||||
Asset.asset_code.ilike(like),
|
||||
Asset.name.ilike(like),
|
||||
PMSchedule.responsible_team.ilike(like),
|
||||
Vendor.name.ilike(like),
|
||||
)
|
||||
)
|
||||
|
||||
total = query.count()
|
||||
rows = (
|
||||
query.order_by(PMSchedule.next_planned_date.asc(), PMSchedule.id.asc())
|
||||
.offset((page - 1) * page_size)
|
||||
.limit(page_size)
|
||||
.all()
|
||||
)
|
||||
cov_map = get_coverage_map(db, [s.asset_id for s in rows], effective_today(db))
|
||||
return maybe_strip_costs_response(
|
||||
PMScheduleListOut(items=[_to_schedule_out(s, cov_map.get(s.asset_id)) for s in rows], total=total),
|
||||
current_user.role,
|
||||
)
|
||||
|
||||
|
||||
@router.post("/schedules", response_model=PMScheduleOut, status_code=status.HTTP_201_CREATED)
|
||||
def create_pm_schedule(
|
||||
payload: PMScheduleCreate,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.coordinator)),
|
||||
):
|
||||
if current_user.role == Role.coordinator.value and payload.cost_per_visit is not None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Only Biomedical or System Admin can edit PM cost per visit.",
|
||||
)
|
||||
|
||||
asset = db.query(Asset).filter(Asset.id == payload.asset_id).first()
|
||||
if asset is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Asset not found.")
|
||||
|
||||
mode = payload.service_mode or str(get_setting_value(db, "default_pm_mode", "in_house"))
|
||||
|
||||
clean_team, provider_id, contract_id, no_active_contract = _validate_schedule_fields(
|
||||
db,
|
||||
asset_id=asset.id,
|
||||
service_mode=mode,
|
||||
responsible_team=payload.responsible_team,
|
||||
provider_id=payload.provider_id,
|
||||
contract_id=payload.contract_id,
|
||||
allow_auto_fill=True,
|
||||
)
|
||||
|
||||
schedule = PMSchedule(
|
||||
asset_id=asset.id,
|
||||
service_mode=mode,
|
||||
frequency_months=payload.frequency_months,
|
||||
responsible_team=clean_team,
|
||||
provider_id=provider_id,
|
||||
contract_id=contract_id,
|
||||
cost_per_visit=payload.cost_per_visit,
|
||||
next_planned_date=payload.next_planned_date,
|
||||
is_active=True,
|
||||
created_by_id=current_user.id,
|
||||
updated_by_id=current_user.id,
|
||||
)
|
||||
db.add(schedule)
|
||||
db.flush()
|
||||
|
||||
initial_record = PMRecord(
|
||||
schedule_id=schedule.id,
|
||||
asset_id=asset.id,
|
||||
planned_date=payload.next_planned_date,
|
||||
status=None,
|
||||
created_by_id=current_user.id,
|
||||
updated_by_id=current_user.id,
|
||||
)
|
||||
db.add(initial_record)
|
||||
db.flush()
|
||||
|
||||
log_audit(
|
||||
db,
|
||||
entity_type="pm_schedule",
|
||||
entity_id=schedule.id,
|
||||
action="create",
|
||||
changes={
|
||||
"asset_id": asset.id,
|
||||
"service_mode": mode,
|
||||
"frequency_months": payload.frequency_months,
|
||||
"next_planned_date": str(payload.next_planned_date),
|
||||
"initial_record_id": initial_record.id,
|
||||
},
|
||||
user_id=current_user.id,
|
||||
)
|
||||
db.commit()
|
||||
|
||||
loaded = _load_schedule_with_joins(db, schedule.id)
|
||||
cov = get_coverage(db, asset.id, effective_today(db))
|
||||
return _to_schedule_out(loaded, cov, no_active_contract=True if no_active_contract else None)
|
||||
|
||||
|
||||
@router.patch("/schedules/{schedule_id}", response_model=PMScheduleOut)
|
||||
def update_pm_schedule(
|
||||
schedule_id: int,
|
||||
payload: PMScheduleUpdate,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.coordinator)),
|
||||
):
|
||||
schedule = db.query(PMSchedule).filter(PMSchedule.id == schedule_id).first()
|
||||
if schedule is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="PM schedule not found.")
|
||||
|
||||
data = payload.model_dump(exclude_unset=True)
|
||||
if current_user.role == Role.coordinator.value and "cost_per_visit" in data:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_403_FORBIDDEN,
|
||||
detail="Only Biomedical or System Admin can edit PM cost per visit.",
|
||||
)
|
||||
target_mode = data.get("service_mode", schedule.service_mode)
|
||||
target_team = data.get("responsible_team", schedule.responsible_team)
|
||||
target_provider = data.get("provider_id", schedule.provider_id)
|
||||
target_contract = data.get("contract_id", schedule.contract_id)
|
||||
|
||||
clean_team, provider_id, contract_id, _ = _validate_schedule_fields(
|
||||
db,
|
||||
asset_id=schedule.asset_id,
|
||||
service_mode=target_mode,
|
||||
responsible_team=target_team,
|
||||
provider_id=target_provider,
|
||||
contract_id=target_contract,
|
||||
allow_auto_fill=True,
|
||||
)
|
||||
data["responsible_team"] = clean_team
|
||||
data["provider_id"] = provider_id
|
||||
data["contract_id"] = contract_id
|
||||
|
||||
changes: dict[str, dict[str, object]] = {}
|
||||
old_next_date = schedule.next_planned_date
|
||||
for k, v in data.items():
|
||||
old_val = getattr(schedule, k)
|
||||
if old_val != v:
|
||||
changes[k] = {"from": old_val, "to": v}
|
||||
setattr(schedule, k, v)
|
||||
schedule.updated_by_id = current_user.id
|
||||
|
||||
if "next_planned_date" in data and schedule.next_planned_date != old_next_date:
|
||||
open_rec = (
|
||||
db.query(PMRecord)
|
||||
.filter(PMRecord.schedule_id == schedule.id, PMRecord.status.is_(None))
|
||||
.order_by(PMRecord.planned_date.desc(), PMRecord.id.desc())
|
||||
.first()
|
||||
)
|
||||
if open_rec is not None:
|
||||
open_rec.planned_date = schedule.next_planned_date
|
||||
open_rec.updated_by_id = current_user.id
|
||||
|
||||
if changes:
|
||||
log_audit(
|
||||
db,
|
||||
entity_type="pm_schedule",
|
||||
entity_id=schedule.id,
|
||||
action="update",
|
||||
changes=changes,
|
||||
user_id=current_user.id,
|
||||
)
|
||||
db.commit()
|
||||
|
||||
loaded = _load_schedule_with_joins(db, schedule.id)
|
||||
cov = get_coverage(db, schedule.asset_id, effective_today(db))
|
||||
return _to_schedule_out(loaded, cov)
|
||||
|
||||
|
||||
@router.delete("/schedules/{schedule_id}", response_model=PMScheduleOut)
|
||||
def deactivate_pm_schedule(
|
||||
schedule_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.coordinator)),
|
||||
):
|
||||
schedule = db.query(PMSchedule).filter(PMSchedule.id == schedule_id).first()
|
||||
if schedule is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="PM schedule not found.")
|
||||
|
||||
if schedule.is_active:
|
||||
schedule.is_active = False
|
||||
schedule.updated_by_id = current_user.id
|
||||
log_audit(
|
||||
db,
|
||||
entity_type="pm_schedule",
|
||||
entity_id=schedule.id,
|
||||
action="deactivate",
|
||||
changes={"is_active": {"from": True, "to": False}},
|
||||
user_id=current_user.id,
|
||||
)
|
||||
db.commit()
|
||||
|
||||
loaded = _load_schedule_with_joins(db, schedule.id)
|
||||
cov = get_coverage(db, schedule.asset_id, effective_today(db))
|
||||
return _to_schedule_out(loaded, cov)
|
||||
|
||||
|
||||
@router.get("/records", response_model=PMRecordListOut)
|
||||
def list_pm_records(
|
||||
q: str = "",
|
||||
month: Optional[str] = None,
|
||||
department_id: Optional[int] = None,
|
||||
asset_id: Optional[int] = None,
|
||||
schedule_id: Optional[int] = None,
|
||||
service_mode: Optional[PMServiceMode] = None,
|
||||
status_filter: Optional[PMRecordStatusFilter] = Query(None, alias="status"),
|
||||
page: int = Query(1, ge=1),
|
||||
page_size: int = Query(200, ge=1, le=500),
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user),
|
||||
):
|
||||
today = effective_today(db)
|
||||
leads = _pm_lead_settings(db)
|
||||
|
||||
query = (
|
||||
db.query(PMRecord)
|
||||
.join(PMSchedule, PMRecord.schedule_id == PMSchedule.id)
|
||||
.join(Asset, PMRecord.asset_id == Asset.id)
|
||||
.outerjoin(Vendor, PMSchedule.provider_id == Vendor.id)
|
||||
.options(
|
||||
joinedload(PMRecord.asset).joinedload(Asset.department),
|
||||
joinedload(PMRecord.asset).joinedload(Asset.location),
|
||||
joinedload(PMRecord.schedule).joinedload(PMSchedule.provider),
|
||||
)
|
||||
)
|
||||
|
||||
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 asset_id is not None:
|
||||
query = query.filter(PMRecord.asset_id == asset_id)
|
||||
if schedule_id is not None:
|
||||
query = query.filter(PMRecord.schedule_id == schedule_id)
|
||||
if service_mode is not None:
|
||||
query = query.filter(PMSchedule.service_mode == service_mode)
|
||||
|
||||
target_year, target_month = today.year, today.month
|
||||
if month is not None and month.strip():
|
||||
m_match = _MONTH_RE.fullmatch(month.strip())
|
||||
if not m_match:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="month must be in YYYY-MM format.",
|
||||
)
|
||||
target_year = int(m_match.group(1))
|
||||
target_month = int(m_match.group(2))
|
||||
month_start = date(target_year, target_month, 1)
|
||||
next_month_start = add_months(month_start, 1)
|
||||
query = query.filter(
|
||||
PMRecord.planned_date >= month_start,
|
||||
PMRecord.planned_date < next_month_start,
|
||||
)
|
||||
|
||||
if q and q.strip():
|
||||
like = f"%{q.strip()}%"
|
||||
query = query.filter(
|
||||
or_(
|
||||
Asset.asset_code.ilike(like),
|
||||
Asset.name.ilike(like),
|
||||
PMSchedule.responsible_team.ilike(like),
|
||||
Vendor.name.ilike(like),
|
||||
PMRecord.service_details.ilike(like),
|
||||
PMRecord.remarks.ilike(like),
|
||||
)
|
||||
)
|
||||
|
||||
rows = query.order_by(PMRecord.planned_date.asc(), PMRecord.id.asc()).all()
|
||||
cov_map = get_coverage_map(db, [r.asset_id for r in rows], today)
|
||||
computed_all = [_to_record_out(r, today, leads, cov_map.get(r.asset_id)) for r in rows]
|
||||
|
||||
upcoming_cnt = sum(1 for item in computed_all if item.status == "upcoming")
|
||||
due_cnt = sum(1 for item in computed_all if item.status == "due")
|
||||
overdue_cnt = sum(1 for item in computed_all if item.status == "overdue")
|
||||
completed_month_cnt = 0
|
||||
for item in computed_all:
|
||||
if item.status == "completed":
|
||||
ref_date = item.completed_date or item.planned_date
|
||||
if (ref_date.year == target_year and ref_date.month == target_month) or (
|
||||
item.planned_date.year == target_year and item.planned_date.month == target_month
|
||||
):
|
||||
completed_month_cnt += 1
|
||||
|
||||
if status_filter is not None:
|
||||
filtered = [item for item in computed_all if item.status == status_filter]
|
||||
else:
|
||||
filtered = computed_all
|
||||
|
||||
total = len(filtered)
|
||||
start = (page - 1) * page_size
|
||||
paginated = filtered[start : start + page_size]
|
||||
|
||||
return PMRecordListOut(
|
||||
items=paginated,
|
||||
total=total,
|
||||
summary=PMRecordSummaryCounts(
|
||||
upcoming=upcoming_cnt,
|
||||
due=due_cnt,
|
||||
overdue=overdue_cnt,
|
||||
completed_this_month=completed_month_cnt,
|
||||
),
|
||||
)
|
||||
|
||||
|
||||
@router.post("/records/{record_id}/complete", response_model=PMRecordCompleteOut)
|
||||
def complete_pm_record(
|
||||
record_id: int,
|
||||
payload: PMRecordCompleteIn,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.coordinator)),
|
||||
):
|
||||
rec = _load_record_with_joins(db, record_id)
|
||||
if rec is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="PM record not found.")
|
||||
|
||||
if rec.status in ("completed", "rescheduled"):
|
||||
raise CodedHTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail=f"PM record is already {rec.status}.",
|
||||
code="INVALID_PM_STATUS",
|
||||
)
|
||||
|
||||
clean_details = payload.service_details.strip()
|
||||
if not clean_details:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="service_details cannot be blank.",
|
||||
)
|
||||
|
||||
rec.status = "completed"
|
||||
rec.completed_date = payload.completed_date
|
||||
rec.service_details = clean_details
|
||||
rec.remarks = payload.remarks.strip() if payload.remarks and payload.remarks.strip() else None
|
||||
rec.updated_by_id = current_user.id
|
||||
|
||||
schedule = rec.schedule
|
||||
next_date = add_months(payload.completed_date, schedule.frequency_months)
|
||||
schedule.next_planned_date = next_date
|
||||
schedule.updated_by_id = current_user.id
|
||||
|
||||
next_rec = PMRecord(
|
||||
schedule_id=schedule.id,
|
||||
asset_id=schedule.asset_id,
|
||||
planned_date=next_date,
|
||||
status=None,
|
||||
created_by_id=current_user.id,
|
||||
updated_by_id=current_user.id,
|
||||
)
|
||||
db.add(next_rec)
|
||||
db.flush()
|
||||
|
||||
log_audit(
|
||||
db,
|
||||
entity_type="pm_record",
|
||||
entity_id=rec.id,
|
||||
action="complete",
|
||||
changes={
|
||||
"completed_date": str(payload.completed_date),
|
||||
"next_planned_date": str(next_date),
|
||||
"next_record_id": next_rec.id,
|
||||
},
|
||||
user_id=current_user.id,
|
||||
)
|
||||
db.commit()
|
||||
|
||||
today = effective_today(db)
|
||||
leads = _pm_lead_settings(db)
|
||||
loaded_completed = _load_record_with_joins(db, rec.id)
|
||||
loaded_next = _load_record_with_joins(db, next_rec.id)
|
||||
cov = get_coverage(db, rec.asset_id, today)
|
||||
return PMRecordCompleteOut(
|
||||
completed_record=_to_record_out(loaded_completed, today, leads, cov),
|
||||
next_record=_to_record_out(loaded_next, today, leads, cov),
|
||||
)
|
||||
|
||||
|
||||
@router.post("/records/{record_id}/reschedule", response_model=PMRecordRescheduleOut)
|
||||
def reschedule_pm_record(
|
||||
record_id: int,
|
||||
payload: PMRecordRescheduleIn,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.coordinator)),
|
||||
):
|
||||
rec = _load_record_with_joins(db, record_id)
|
||||
if rec is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="PM record not found.")
|
||||
|
||||
if rec.status in ("completed", "rescheduled"):
|
||||
raise CodedHTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail=f"PM record is already {rec.status}.",
|
||||
code="INVALID_PM_STATUS",
|
||||
)
|
||||
|
||||
rec.status = "rescheduled"
|
||||
rec.rescheduled_to = payload.rescheduled_to
|
||||
rec.remarks = payload.remarks.strip() if payload.remarks and payload.remarks.strip() else None
|
||||
rec.updated_by_id = current_user.id
|
||||
|
||||
schedule = rec.schedule
|
||||
schedule.next_planned_date = payload.rescheduled_to
|
||||
schedule.updated_by_id = current_user.id
|
||||
|
||||
next_rec = PMRecord(
|
||||
schedule_id=schedule.id,
|
||||
asset_id=schedule.asset_id,
|
||||
planned_date=payload.rescheduled_to,
|
||||
status=None,
|
||||
created_by_id=current_user.id,
|
||||
updated_by_id=current_user.id,
|
||||
)
|
||||
db.add(next_rec)
|
||||
db.flush()
|
||||
|
||||
log_audit(
|
||||
db,
|
||||
entity_type="pm_record",
|
||||
entity_id=rec.id,
|
||||
action="reschedule",
|
||||
changes={
|
||||
"rescheduled_to": str(payload.rescheduled_to),
|
||||
"next_record_id": next_rec.id,
|
||||
},
|
||||
user_id=current_user.id,
|
||||
)
|
||||
db.commit()
|
||||
|
||||
today = effective_today(db)
|
||||
leads = _pm_lead_settings(db)
|
||||
loaded_rescheduled = _load_record_with_joins(db, rec.id)
|
||||
loaded_next = _load_record_with_joins(db, next_rec.id)
|
||||
cov = get_coverage(db, rec.asset_id, today)
|
||||
return PMRecordRescheduleOut(
|
||||
rescheduled_record=_to_record_out(loaded_rescheduled, today, leads, cov),
|
||||
next_record=_to_record_out(loaded_next, today, leads, cov),
|
||||
)
|
||||
@@ -0,0 +1,87 @@
|
||||
from datetime import date
|
||||
from typing import Any, Literal
|
||||
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
from fastapi.responses import StreamingResponse
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..core.db import get_db
|
||||
from ..core.deps import get_current_user
|
||||
from ..models import User
|
||||
from ..services.exports import build_csv, build_xlsx
|
||||
from ..services.reports_service import generate_report
|
||||
|
||||
router = APIRouter(prefix="/reports", tags=["reports"])
|
||||
|
||||
|
||||
def _report_params(
|
||||
month: str | None = Query(None),
|
||||
date_from: date | None = Query(None),
|
||||
date_to: date | None = Query(None),
|
||||
due_from: date | None = Query(None),
|
||||
due_to: date | None = Query(None),
|
||||
department_id: int | None = Query(None),
|
||||
asset_id: int | None = Query(None),
|
||||
priority: str | None = Query(None),
|
||||
call_status: str | None = Query(None),
|
||||
assigned_to_id: int | None = Query(None),
|
||||
service_mode: str | None = Query(None),
|
||||
agency_id: int | None = Query(None),
|
||||
status: str | None = Query(None),
|
||||
record_kind: str | None = Query(None),
|
||||
contract_type: str | None = Query(None),
|
||||
supplier_id: int | None = Query(None),
|
||||
) -> dict[str, Any]:
|
||||
return {
|
||||
"month": month,
|
||||
"date_from": date_from,
|
||||
"date_to": date_to,
|
||||
"due_from": due_from,
|
||||
"due_to": due_to,
|
||||
"department_id": department_id,
|
||||
"asset_id": asset_id,
|
||||
"priority": priority,
|
||||
"call_status": call_status,
|
||||
"assigned_to_id": assigned_to_id,
|
||||
"service_mode": service_mode,
|
||||
"agency_id": agency_id,
|
||||
"status": status,
|
||||
"record_kind": record_kind,
|
||||
"contract_type": contract_type,
|
||||
"supplier_id": supplier_id,
|
||||
}
|
||||
|
||||
|
||||
@router.get("/{report_key}")
|
||||
def get_report(
|
||||
report_key: str,
|
||||
params: dict[str, Any] = Depends(_report_params),
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user),
|
||||
):
|
||||
return generate_report(db, current_user, report_key, params)
|
||||
|
||||
|
||||
@router.get("/{report_key}/export")
|
||||
def export_report(
|
||||
report_key: str,
|
||||
format: Literal["xlsx", "csv"] = Query("xlsx"),
|
||||
params: dict[str, Any] = Depends(_report_params),
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user),
|
||||
):
|
||||
payload = generate_report(db, current_user, report_key, params)
|
||||
if format == "csv":
|
||||
buf = build_csv(payload)
|
||||
media_type = "text/csv; charset=utf-8"
|
||||
else:
|
||||
buf = build_xlsx(payload)
|
||||
media_type = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
|
||||
|
||||
return StreamingResponse(
|
||||
buf,
|
||||
media_type=media_type,
|
||||
headers={
|
||||
"Content-Disposition": f'attachment; filename="{report_key}.{format}"',
|
||||
},
|
||||
)
|
||||
@@ -0,0 +1,88 @@
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
from sqlalchemy import or_
|
||||
from sqlalchemy.orm import Session, joinedload
|
||||
|
||||
from ..core.db import get_db
|
||||
from ..core.deps import get_current_user
|
||||
from ..models import Asset, Complaint, User
|
||||
from ..services.permissions import Role
|
||||
from ..services.scoping import resolve_department_scope
|
||||
|
||||
router = APIRouter(prefix="/search", tags=["search"])
|
||||
|
||||
|
||||
@router.get("")
|
||||
def global_search(
|
||||
q: str = Query(..., min_length=1),
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user),
|
||||
):
|
||||
term = q.strip()
|
||||
if not term:
|
||||
return {"assets": [], "complaints": []}
|
||||
|
||||
scope = resolve_department_scope(current_user)
|
||||
if scope.is_empty:
|
||||
return {"assets": [], "complaints": []}
|
||||
|
||||
pattern = f"%{term}%"
|
||||
|
||||
asset_q = db.query(Asset).options(joinedload(Asset.department)).filter(
|
||||
or_(
|
||||
Asset.asset_code.ilike(pattern),
|
||||
Asset.name.ilike(pattern),
|
||||
Asset.serial_no.ilike(pattern),
|
||||
)
|
||||
)
|
||||
if scope.department_id is not None:
|
||||
asset_q = asset_q.filter(Asset.department_id == scope.department_id)
|
||||
assets = asset_q.order_by(Asset.asset_code.asc()).limit(8).all()
|
||||
|
||||
complaint_q = (
|
||||
db.query(Complaint)
|
||||
.join(Asset, Complaint.asset_id == Asset.id)
|
||||
.options(joinedload(Complaint.asset).joinedload(Asset.department))
|
||||
.filter(
|
||||
or_(
|
||||
Complaint.complaint_no.ilike(pattern),
|
||||
Complaint.description.ilike(pattern),
|
||||
Asset.asset_code.ilike(pattern),
|
||||
Asset.name.ilike(pattern),
|
||||
)
|
||||
)
|
||||
)
|
||||
if scope.department_id is not None:
|
||||
complaint_q = complaint_q.filter(Asset.department_id == scope.department_id)
|
||||
complaints = (
|
||||
complaint_q.order_by(Complaint.registered_at.desc(), Complaint.id.desc())
|
||||
.limit(8)
|
||||
.all()
|
||||
)
|
||||
|
||||
return {
|
||||
"assets": [
|
||||
{
|
||||
"id": a.id,
|
||||
"asset_code": a.asset_code,
|
||||
"name": a.name,
|
||||
"serial_no": a.serial_no,
|
||||
"department_name": a.department.name if a.department else "—",
|
||||
"status": a.status,
|
||||
}
|
||||
for a in assets
|
||||
],
|
||||
"complaints": [
|
||||
{
|
||||
"id": c.id,
|
||||
"complaint_no": c.complaint_no,
|
||||
"asset_code": c.asset.asset_code if c.asset else "—",
|
||||
"asset_name": c.asset.name if c.asset else "—",
|
||||
"department_name": (
|
||||
c.asset.department.name if c.asset and c.asset.department else "—"
|
||||
),
|
||||
"call_status": c.call_status,
|
||||
"priority": c.priority,
|
||||
}
|
||||
for c in complaints
|
||||
],
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
from fastapi import APIRouter, Depends
|
||||
from sqlalchemy.orm import Session
|
||||
from ..core.db import get_db
|
||||
from ..core.deps import require_roles
|
||||
from ..core.time_utils import effective_today
|
||||
from ..models.masters import User
|
||||
from ..schemas.settings import DemoDateIn, DemoDateOut, SettingsListOut, SettingsUpdateIn
|
||||
from ..services.permissions import Role
|
||||
from ..services.settings_service import get_all_settings, get_demo_as_of_date, update_settings
|
||||
|
||||
router = APIRouter(prefix="/settings", tags=["settings"])
|
||||
|
||||
|
||||
@router.get("", response_model=SettingsListOut)
|
||||
def list_settings(
|
||||
db: Session = Depends(get_db),
|
||||
_: User = Depends(require_roles(Role.system_admin)),
|
||||
):
|
||||
return {"items": get_all_settings(db)}
|
||||
|
||||
|
||||
@router.put("", response_model=SettingsListOut)
|
||||
def save_settings(
|
||||
payload: SettingsUpdateIn,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(Role.system_admin)),
|
||||
):
|
||||
items = update_settings(db, payload.values, user_id=current_user.id)
|
||||
return {"items": items}
|
||||
|
||||
|
||||
@router.post("/demo-date", response_model=DemoDateOut)
|
||||
def set_demo_date(
|
||||
payload: DemoDateIn,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(Role.system_admin)),
|
||||
):
|
||||
val = payload.demo_as_of_date if payload.demo_as_of_date is not None else ""
|
||||
update_settings(db, {"demo_as_of_date": val}, user_id=current_user.id)
|
||||
return {
|
||||
"demo_as_of_date": get_demo_as_of_date(db),
|
||||
"effective_today": effective_today(db).isoformat(),
|
||||
}
|
||||
@@ -0,0 +1,249 @@
|
||||
from typing import Optional
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, status
|
||||
from pydantic import BaseModel, Field
|
||||
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.security import hash_password, validate_password
|
||||
from ..models.masters import Department, User
|
||||
from ..schemas.masters import (
|
||||
PaginatedOut,
|
||||
UserCreate,
|
||||
UserListOut,
|
||||
UserLookupOut,
|
||||
UserUpdate,
|
||||
)
|
||||
from ..services.permissions import Role
|
||||
|
||||
router = APIRouter(prefix="/users", tags=["users"])
|
||||
|
||||
|
||||
class ResetPasswordRequest(BaseModel):
|
||||
new_password: str = Field(..., max_length=128)
|
||||
|
||||
|
||||
def _user_list_out(user: User) -> UserListOut:
|
||||
return UserListOut(
|
||||
id=user.id,
|
||||
name=user.name,
|
||||
email=user.email,
|
||||
role=user.role,
|
||||
department_id=user.department_id,
|
||||
department_name=user.department.name if user.department else None,
|
||||
is_active=user.is_active,
|
||||
)
|
||||
|
||||
|
||||
@router.get("", response_model=PaginatedOut[UserListOut])
|
||||
def list_users(
|
||||
q: Optional[str] = None,
|
||||
role: Optional[str] = None,
|
||||
page: int = Query(1, ge=1),
|
||||
page_size: int = Query(100, ge=0, le=500),
|
||||
include_inactive: bool = False,
|
||||
db: Session = Depends(get_db),
|
||||
_: User = Depends(require_roles(Role.system_admin)),
|
||||
):
|
||||
query = db.query(User).options(joinedload(User.department))
|
||||
if not include_inactive:
|
||||
query = query.filter(User.is_active.is_(True))
|
||||
if role:
|
||||
query = query.filter(User.role == role)
|
||||
if q and q.strip():
|
||||
like = f"%{q.strip()}%"
|
||||
query = query.filter(or_(User.name.ilike(like), User.email.ilike(like)))
|
||||
query = query.order_by(User.name.asc())
|
||||
total = query.count()
|
||||
if page_size > 0:
|
||||
query = query.offset((page - 1) * page_size).limit(page_size)
|
||||
items = query.all()
|
||||
return {"items": [_user_list_out(u) for u in items], "total": total}
|
||||
|
||||
|
||||
@router.get("/lookup", response_model=PaginatedOut[UserLookupOut])
|
||||
def lookup_users(
|
||||
db: Session = Depends(get_db),
|
||||
_: User = Depends(get_current_user),
|
||||
):
|
||||
users = (
|
||||
db.query(User)
|
||||
.filter(User.is_active.is_(True))
|
||||
.order_by(User.name.asc())
|
||||
.all()
|
||||
)
|
||||
return {"items": users, "total": len(users)}
|
||||
|
||||
|
||||
@router.post("", response_model=UserListOut, status_code=status.HTTP_201_CREATED)
|
||||
def create_user(
|
||||
payload: UserCreate,
|
||||
db: Session = Depends(get_db),
|
||||
_: User = Depends(require_roles(Role.system_admin)),
|
||||
):
|
||||
if payload.role == "department_user" and payload.department_id is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="Department is required for department_user role.",
|
||||
)
|
||||
|
||||
if payload.department_id is not None:
|
||||
dept = db.query(Department).filter(Department.id == payload.department_id).first()
|
||||
if dept is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Department not found.")
|
||||
|
||||
validate_password(payload.password, email=payload.email)
|
||||
|
||||
user = User(
|
||||
name=payload.name.strip(),
|
||||
email=payload.email.strip().lower(),
|
||||
password_hash=hash_password(payload.password),
|
||||
role=payload.role,
|
||||
department_id=payload.department_id,
|
||||
is_active=payload.is_active,
|
||||
)
|
||||
db.add(user)
|
||||
try:
|
||||
db.commit()
|
||||
except IntegrityError:
|
||||
db.rollback()
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail="A user with this email already exists.",
|
||||
)
|
||||
user = db.query(User).options(joinedload(User.department)).filter(User.id == user.id).first()
|
||||
return _user_list_out(user)
|
||||
|
||||
|
||||
@router.patch("/{user_id}", response_model=UserListOut)
|
||||
def update_user(
|
||||
user_id: int,
|
||||
payload: UserUpdate,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(Role.system_admin)),
|
||||
):
|
||||
user = db.query(User).options(joinedload(User.department)).filter(User.id == user_id).first()
|
||||
if user is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found.")
|
||||
|
||||
data = payload.model_dump(exclude_unset=True)
|
||||
|
||||
# Department user validation
|
||||
target_role = data.get("role", user.role)
|
||||
target_dept = data.get("department_id", user.department_id)
|
||||
if target_role == "department_user" and target_dept is None:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="Department is required for department_user role.",
|
||||
)
|
||||
|
||||
# Prevent self-deactivation or changing own admin role
|
||||
if user.id == current_user.id:
|
||||
if "is_active" in data and not data["is_active"]:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Cannot deactivate your own administrator account.",
|
||||
)
|
||||
if "role" in data and data["role"] != "system_admin":
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Cannot change the role of your own administrator account.",
|
||||
)
|
||||
|
||||
# Prevent deactivating or demoting the last active system admin
|
||||
if user.role == "system_admin" and (
|
||||
("is_active" in data and not data["is_active"])
|
||||
or ("role" in data and data["role"] != "system_admin")
|
||||
):
|
||||
active_admins = (
|
||||
db.query(User)
|
||||
.filter(User.role == "system_admin", User.is_active.is_(True), User.id != user.id)
|
||||
.count()
|
||||
)
|
||||
if active_admins == 0:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Cannot deactivate or change role: system must have at least one active system administrator.",
|
||||
)
|
||||
|
||||
if "department_id" in data and data["department_id"] is not None:
|
||||
dept = db.query(Department).filter(Department.id == data["department_id"]).first()
|
||||
if dept is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Department not found.")
|
||||
if "name" in data and data["name"] is not None:
|
||||
data["name"] = data["name"].strip()
|
||||
if "email" in data and data["email"] is not None:
|
||||
data["email"] = data["email"].strip().lower()
|
||||
|
||||
password = data.pop("password", None)
|
||||
if password is not None and password != "":
|
||||
validate_password(password, email=data.get("email", user.email))
|
||||
user.password_hash = hash_password(password)
|
||||
user.token_version = (user.token_version or 0) + 1
|
||||
|
||||
for k, v in data.items():
|
||||
setattr(user, k, v)
|
||||
|
||||
try:
|
||||
db.commit()
|
||||
except IntegrityError:
|
||||
db.rollback()
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_409_CONFLICT,
|
||||
detail="A user with this email already exists.",
|
||||
)
|
||||
db.refresh(user)
|
||||
user = db.query(User).options(joinedload(User.department)).filter(User.id == user.id).first()
|
||||
return _user_list_out(user)
|
||||
|
||||
|
||||
@router.delete("/{user_id}", response_model=UserListOut)
|
||||
def delete_user(
|
||||
user_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(Role.system_admin)),
|
||||
):
|
||||
if user_id == current_user.id:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Cannot delete your own administrator account.",
|
||||
)
|
||||
|
||||
user = db.query(User).options(joinedload(User.department)).filter(User.id == user_id).first()
|
||||
if user is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found.")
|
||||
|
||||
if user.role == "system_admin":
|
||||
active_admins = (
|
||||
db.query(User)
|
||||
.filter(User.role == "system_admin", User.is_active.is_(True), User.id != user.id)
|
||||
.count()
|
||||
)
|
||||
if active_admins == 0:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_400_BAD_REQUEST,
|
||||
detail="Cannot delete the only active system administrator account.",
|
||||
)
|
||||
|
||||
user.is_active = False
|
||||
db.commit()
|
||||
db.refresh(user)
|
||||
return _user_list_out(user)
|
||||
|
||||
|
||||
@router.post("/{user_id}/reset-password")
|
||||
def reset_user_password(
|
||||
user_id: int,
|
||||
payload: ResetPasswordRequest,
|
||||
db: Session = Depends(get_db),
|
||||
_: User = Depends(require_roles(Role.system_admin)),
|
||||
):
|
||||
user = db.query(User).filter(User.id == user_id).first()
|
||||
if user is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="User not found.")
|
||||
validate_password(payload.new_password, email=user.email)
|
||||
user.password_hash = hash_password(payload.new_password)
|
||||
user.token_version = (user.token_version or 0) + 1
|
||||
db.commit()
|
||||
return {"message": f"Password for {user.name} has been reset successfully."}
|
||||
@@ -0,0 +1,344 @@
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Response, status
|
||||
from sqlalchemy import or_
|
||||
from sqlalchemy.orm import Session, joinedload
|
||||
|
||||
from ..core.db import get_db
|
||||
from ..core.deps import require_roles
|
||||
from ..models import Asset, Complaint, Department, DepartmentVisit, User
|
||||
from ..schemas.visits import (
|
||||
VisitAssetSummary,
|
||||
VisitComplaintSummary,
|
||||
VisitCreate,
|
||||
VisitLinkComplaintIn,
|
||||
VisitListOut,
|
||||
VisitOut,
|
||||
VisitUpdate,
|
||||
)
|
||||
from ..services.audit import log_audit
|
||||
from ..services.permissions import Role
|
||||
|
||||
router = APIRouter(prefix="/visits", tags=["visits"])
|
||||
|
||||
|
||||
def _to_visit_out(v: DepartmentVisit) -> VisitOut:
|
||||
return VisitOut(
|
||||
id=v.id,
|
||||
department_id=v.department_id,
|
||||
department_name=v.department.name if v.department else None,
|
||||
visited_by_id=v.visited_by_id,
|
||||
visited_by_name=v.visited_by.name if v.visited_by else None,
|
||||
visit_date=v.visit_date,
|
||||
observations=v.observations,
|
||||
new_requirements=v.new_requirements,
|
||||
assets=[
|
||||
VisitAssetSummary(id=a.id, asset_code=a.asset_code, name=a.name)
|
||||
for a in v.assets
|
||||
],
|
||||
complaints=[
|
||||
VisitComplaintSummary(
|
||||
id=c.id,
|
||||
complaint_no=c.complaint_no,
|
||||
call_status=c.call_status,
|
||||
priority=c.priority,
|
||||
description=c.description,
|
||||
)
|
||||
for c in v.complaints
|
||||
],
|
||||
created_at=v.created_at,
|
||||
)
|
||||
|
||||
|
||||
def _load_visit(db: Session, visit_id: int) -> DepartmentVisit | None:
|
||||
return (
|
||||
db.query(DepartmentVisit)
|
||||
.options(
|
||||
joinedload(DepartmentVisit.department),
|
||||
joinedload(DepartmentVisit.visited_by),
|
||||
joinedload(DepartmentVisit.assets),
|
||||
joinedload(DepartmentVisit.complaints),
|
||||
)
|
||||
.filter(DepartmentVisit.id == visit_id)
|
||||
.first()
|
||||
)
|
||||
|
||||
|
||||
def _resolve_assets_and_complaints(
|
||||
db: Session,
|
||||
asset_ids: list[int] | None,
|
||||
complaint_ids: list[int] | None,
|
||||
) -> tuple[list[Asset] | None, list[Complaint] | None]:
|
||||
assets_list: list[Asset] | None = None
|
||||
complaints_list: list[Complaint] | None = None
|
||||
|
||||
if asset_ids is not None:
|
||||
unique_aids = list(dict.fromkeys(asset_ids))
|
||||
if unique_aids:
|
||||
found_assets = db.query(Asset).filter(Asset.id.in_(unique_aids)).all()
|
||||
by_id = {a.id: a for a in found_assets}
|
||||
missing = [aid for aid in unique_aids if aid not in by_id]
|
||||
if missing:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail=f"Assets not found: {missing}",
|
||||
)
|
||||
assets_list = [by_id[aid] for aid in unique_aids]
|
||||
else:
|
||||
assets_list = []
|
||||
|
||||
if complaint_ids is not None:
|
||||
unique_cids = list(dict.fromkeys(complaint_ids))
|
||||
if unique_cids:
|
||||
found_cmps = db.query(Complaint).filter(Complaint.id.in_(unique_cids)).all()
|
||||
by_id = {c.id: c for c in found_cmps}
|
||||
missing = [cid for cid in unique_cids if cid not in by_id]
|
||||
if missing:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_404_NOT_FOUND,
|
||||
detail=f"Complaints not found: {missing}",
|
||||
)
|
||||
complaints_list = [by_id[cid] for cid in unique_cids]
|
||||
else:
|
||||
complaints_list = []
|
||||
|
||||
return assets_list, complaints_list
|
||||
|
||||
|
||||
@router.get("", response_model=VisitListOut)
|
||||
def list_visits(
|
||||
q: str = "",
|
||||
department_id: Optional[int] = None,
|
||||
visited_by_id: Optional[int] = None,
|
||||
date_from: Optional[date] = None,
|
||||
date_to: Optional[date] = None,
|
||||
page: int = Query(1, ge=1),
|
||||
page_size: int = Query(200, ge=1, le=500),
|
||||
db: Session = Depends(get_db),
|
||||
_: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.management)),
|
||||
):
|
||||
query = (
|
||||
db.query(DepartmentVisit)
|
||||
.join(Department, DepartmentVisit.department_id == Department.id)
|
||||
.join(User, DepartmentVisit.visited_by_id == User.id)
|
||||
.options(
|
||||
joinedload(DepartmentVisit.department),
|
||||
joinedload(DepartmentVisit.visited_by),
|
||||
joinedload(DepartmentVisit.assets),
|
||||
joinedload(DepartmentVisit.complaints),
|
||||
)
|
||||
)
|
||||
if department_id is not None:
|
||||
query = query.filter(DepartmentVisit.department_id == department_id)
|
||||
if visited_by_id is not None:
|
||||
query = query.filter(DepartmentVisit.visited_by_id == visited_by_id)
|
||||
if date_from is not None:
|
||||
query = query.filter(DepartmentVisit.visit_date >= date_from)
|
||||
if date_to is not None:
|
||||
query = query.filter(DepartmentVisit.visit_date <= date_to)
|
||||
if q and q.strip():
|
||||
like = f"%{q.strip()}%"
|
||||
query = query.filter(
|
||||
or_(
|
||||
DepartmentVisit.observations.ilike(like),
|
||||
Department.name.ilike(like),
|
||||
User.name.ilike(like),
|
||||
)
|
||||
)
|
||||
|
||||
total = query.count()
|
||||
rows = (
|
||||
query.order_by(DepartmentVisit.visit_date.desc(), DepartmentVisit.id.desc())
|
||||
.offset((page - 1) * page_size)
|
||||
.limit(page_size)
|
||||
.all()
|
||||
)
|
||||
return VisitListOut(items=[_to_visit_out(r) for r in rows], total=total)
|
||||
|
||||
|
||||
@router.get("/{visit_id}", response_model=VisitOut)
|
||||
def get_visit(
|
||||
visit_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
_: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.management)),
|
||||
):
|
||||
visit = _load_visit(db, visit_id)
|
||||
if visit is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Visit not found.")
|
||||
return _to_visit_out(visit)
|
||||
|
||||
|
||||
@router.post("", response_model=VisitOut, status_code=status.HTTP_201_CREATED)
|
||||
def create_visit(
|
||||
payload: VisitCreate,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical)),
|
||||
):
|
||||
if not db.query(Department.id).filter(Department.id == payload.department_id).first():
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Department not found.")
|
||||
|
||||
clean_obs = payload.observations.strip()
|
||||
if not clean_obs:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="observations cannot be blank.",
|
||||
)
|
||||
|
||||
visited_by_id = current_user.id
|
||||
if current_user.role == Role.system_admin.value and payload.visited_by_id is not None:
|
||||
if not db.query(User.id).filter(User.id == payload.visited_by_id).first():
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Visited-by user not found.")
|
||||
visited_by_id = payload.visited_by_id
|
||||
|
||||
assets_list, complaints_list = _resolve_assets_and_complaints(
|
||||
db, payload.asset_ids, payload.complaint_ids
|
||||
)
|
||||
|
||||
visit = DepartmentVisit(
|
||||
department_id=payload.department_id,
|
||||
visited_by_id=visited_by_id,
|
||||
visit_date=payload.visit_date,
|
||||
observations=clean_obs,
|
||||
new_requirements=payload.new_requirements.strip() if payload.new_requirements else None,
|
||||
created_by_id=current_user.id,
|
||||
updated_by_id=current_user.id,
|
||||
)
|
||||
if assets_list is not None:
|
||||
visit.assets = assets_list
|
||||
if complaints_list is not None:
|
||||
visit.complaints = complaints_list
|
||||
|
||||
db.add(visit)
|
||||
db.flush()
|
||||
|
||||
log_audit(
|
||||
db,
|
||||
entity_type="department_visit",
|
||||
entity_id=visit.id,
|
||||
action="create",
|
||||
changes={
|
||||
"department_id": payload.department_id,
|
||||
"visit_date": str(payload.visit_date),
|
||||
"asset_ids": [a.id for a in visit.assets],
|
||||
"complaint_ids": [c.id for c in visit.complaints],
|
||||
},
|
||||
user_id=current_user.id,
|
||||
)
|
||||
db.commit()
|
||||
|
||||
loaded = _load_visit(db, visit.id)
|
||||
return _to_visit_out(loaded)
|
||||
|
||||
|
||||
@router.patch("/{visit_id}", response_model=VisitOut)
|
||||
def update_visit(
|
||||
visit_id: int,
|
||||
payload: VisitUpdate,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical)),
|
||||
):
|
||||
visit = _load_visit(db, visit_id)
|
||||
if visit is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Visit not found.")
|
||||
|
||||
data = payload.model_dump(exclude_unset=True)
|
||||
if "department_id" in data and data["department_id"] is not None:
|
||||
if not db.query(Department.id).filter(Department.id == data["department_id"]).first():
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Department not found.")
|
||||
visit.department_id = data["department_id"]
|
||||
if "visit_date" in data and data["visit_date"] is not None:
|
||||
visit.visit_date = data["visit_date"]
|
||||
if "observations" in data and data["observations"] is not None:
|
||||
clean_obs = data["observations"].strip()
|
||||
if not clean_obs:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="observations cannot be blank.",
|
||||
)
|
||||
visit.observations = clean_obs
|
||||
if "new_requirements" in data:
|
||||
req = data["new_requirements"]
|
||||
visit.new_requirements = req.strip() if isinstance(req, str) and req.strip() else None
|
||||
|
||||
assets_list, complaints_list = _resolve_assets_and_complaints(
|
||||
db,
|
||||
data["asset_ids"] if "asset_ids" in data else None,
|
||||
data["complaint_ids"] if "complaint_ids" in data else None,
|
||||
)
|
||||
if assets_list is not None:
|
||||
visit.assets = assets_list
|
||||
if complaints_list is not None:
|
||||
visit.complaints = complaints_list
|
||||
|
||||
visit.updated_by_id = current_user.id
|
||||
log_audit(
|
||||
db,
|
||||
entity_type="department_visit",
|
||||
entity_id=visit.id,
|
||||
action="update",
|
||||
changes={"updated_fields": list(data.keys())},
|
||||
user_id=current_user.id,
|
||||
)
|
||||
db.commit()
|
||||
|
||||
loaded = _load_visit(db, visit.id)
|
||||
return _to_visit_out(loaded)
|
||||
|
||||
|
||||
@router.delete("/{visit_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
def delete_visit(
|
||||
visit_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical)),
|
||||
):
|
||||
visit = _load_visit(db, visit_id)
|
||||
if visit is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Visit not found.")
|
||||
|
||||
visit.assets = []
|
||||
visit.complaints = []
|
||||
db.flush()
|
||||
|
||||
log_audit(
|
||||
db,
|
||||
entity_type="department_visit",
|
||||
entity_id=visit.id,
|
||||
action="delete",
|
||||
changes={"department_id": visit.department_id, "visit_date": str(visit.visit_date)},
|
||||
user_id=current_user.id,
|
||||
)
|
||||
db.delete(visit)
|
||||
db.commit()
|
||||
return Response(status_code=status.HTTP_204_NO_CONTENT)
|
||||
|
||||
|
||||
@router.post("/{visit_id}/link-complaint", response_model=VisitOut)
|
||||
def link_complaint_to_visit(
|
||||
visit_id: int,
|
||||
payload: VisitLinkComplaintIn,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical)),
|
||||
):
|
||||
visit = _load_visit(db, visit_id)
|
||||
if visit is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Visit not found.")
|
||||
|
||||
complaint = db.query(Complaint).filter(Complaint.id == payload.complaint_id).first()
|
||||
if complaint is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Complaint not found.")
|
||||
|
||||
if all(c.id != complaint.id for c in visit.complaints):
|
||||
visit.complaints.append(complaint)
|
||||
visit.updated_by_id = current_user.id
|
||||
log_audit(
|
||||
db,
|
||||
entity_type="department_visit",
|
||||
entity_id=visit.id,
|
||||
action="link_complaint",
|
||||
changes={"complaint_id": complaint.id, "complaint_no": complaint.complaint_no},
|
||||
user_id=current_user.id,
|
||||
)
|
||||
db.commit()
|
||||
|
||||
loaded = _load_visit(db, visit.id)
|
||||
return _to_visit_out(loaded)
|
||||
@@ -0,0 +1,274 @@
|
||||
from datetime import date
|
||||
from typing import Optional
|
||||
from fastapi import APIRouter, Depends, HTTPException, Query, Response, status
|
||||
from sqlalchemy import or_
|
||||
from sqlalchemy.orm import Session, joinedload
|
||||
|
||||
from ..core.db import get_db
|
||||
from ..core.deps import get_current_user, require_roles
|
||||
from ..core.time_utils import add_months, effective_today
|
||||
from ..models import Asset, User, Vendor, Warranty
|
||||
from ..schemas.warranties import (
|
||||
CoverageStatusFilter,
|
||||
WarrantyCreate,
|
||||
WarrantyListOut,
|
||||
WarrantyOut,
|
||||
WarrantyUpdate,
|
||||
)
|
||||
from ..services.attachment_service import get_attachment_counts
|
||||
from ..services.audit import log_audit
|
||||
from ..services.calculations import coverage_status
|
||||
from ..services.permissions import Role
|
||||
from ..services.settings_service import get_setting_value
|
||||
|
||||
router = APIRouter(prefix="/warranties", tags=["warranties"])
|
||||
|
||||
|
||||
def _warranty_lead_settings(db: Session) -> tuple[int, int]:
|
||||
lead = int(
|
||||
get_setting_value(
|
||||
db,
|
||||
"warranty_lead_days",
|
||||
get_setting_value(db, "warranty_expiry_alert_days", 30),
|
||||
)
|
||||
)
|
||||
red = int(get_setting_value(db, "red_threshold_days", 7))
|
||||
return lead, red
|
||||
|
||||
|
||||
def _to_warranty_out(
|
||||
w: Warranty,
|
||||
today: date,
|
||||
lead_days: int,
|
||||
red_days: int,
|
||||
att_counts: dict[int, int],
|
||||
) -> WarrantyOut:
|
||||
asset = w.asset
|
||||
st, sev = coverage_status(w.start_date, w.end_date, today, lead_days, red_days)
|
||||
return WarrantyOut(
|
||||
id=w.id,
|
||||
asset_id=w.asset_id,
|
||||
asset_code=asset.asset_code,
|
||||
asset_name=asset.name,
|
||||
department_id=asset.department_id,
|
||||
department_name=asset.department.name if asset.department else None,
|
||||
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,
|
||||
days_to_expiry=(w.end_date - today).days,
|
||||
attachment_count=att_counts.get(w.id, 0),
|
||||
remarks=w.remarks,
|
||||
created_at=w.created_at,
|
||||
)
|
||||
|
||||
|
||||
def _load_warranty(db: Session, warranty_id: int) -> Warranty | None:
|
||||
return (
|
||||
db.query(Warranty)
|
||||
.options(
|
||||
joinedload(Warranty.asset).joinedload(Asset.department),
|
||||
joinedload(Warranty.provider),
|
||||
)
|
||||
.filter(Warranty.id == warranty_id)
|
||||
.first()
|
||||
)
|
||||
|
||||
|
||||
@router.get("", response_model=WarrantyListOut)
|
||||
def list_warranties(
|
||||
q: str = "",
|
||||
department_id: Optional[int] = None,
|
||||
asset_id: Optional[int] = None,
|
||||
status_filter: Optional[CoverageStatusFilter] = Query(None, alias="status"),
|
||||
expiry_from: Optional[date] = None,
|
||||
expiry_to: Optional[date] = None,
|
||||
page: int = Query(1, ge=1),
|
||||
page_size: int = Query(200, ge=1, le=500),
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(get_current_user),
|
||||
):
|
||||
today = effective_today(db)
|
||||
lead_days, red_days = _warranty_lead_settings(db)
|
||||
|
||||
query = (
|
||||
db.query(Warranty)
|
||||
.join(Asset, Warranty.asset_id == Asset.id)
|
||||
.outerjoin(Vendor, Warranty.provider_id == Vendor.id)
|
||||
.options(
|
||||
joinedload(Warranty.asset).joinedload(Asset.department),
|
||||
joinedload(Warranty.provider),
|
||||
)
|
||||
)
|
||||
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 asset_id is not None:
|
||||
query = query.filter(Warranty.asset_id == asset_id)
|
||||
if expiry_from is not None:
|
||||
query = query.filter(Warranty.end_date >= expiry_from)
|
||||
if expiry_to is not None:
|
||||
query = query.filter(Warranty.end_date <= expiry_to)
|
||||
if q and q.strip():
|
||||
like = f"%{q.strip()}%"
|
||||
query = query.filter(
|
||||
or_(
|
||||
Asset.asset_code.ilike(like),
|
||||
Asset.name.ilike(like),
|
||||
Vendor.name.ilike(like),
|
||||
Warranty.remarks.ilike(like),
|
||||
)
|
||||
)
|
||||
|
||||
rows = query.order_by(Warranty.end_date.asc(), Warranty.id.desc()).all()
|
||||
att_counts = get_attachment_counts(db, "warranty", [r.id for r in rows])
|
||||
items_all = [_to_warranty_out(r, today, lead_days, red_days, att_counts) for r in rows]
|
||||
|
||||
if status_filter is not None:
|
||||
items_all = [item for item in items_all if item.status == status_filter]
|
||||
|
||||
total = len(items_all)
|
||||
start = (page - 1) * page_size
|
||||
return WarrantyListOut(items=items_all[start : start + page_size], total=total)
|
||||
|
||||
|
||||
@router.post("", response_model=WarrantyOut, status_code=status.HTTP_201_CREATED)
|
||||
def create_warranty(
|
||||
payload: WarrantyCreate,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.coordinator)),
|
||||
):
|
||||
if not db.query(Asset.id).filter(Asset.id == payload.asset_id).first():
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Asset not found.")
|
||||
if payload.provider_id is not None:
|
||||
if not db.query(Vendor.id).filter(Vendor.id == payload.provider_id).first():
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Provider vendor not found.")
|
||||
|
||||
computed_end = payload.end_date or add_months(payload.start_date, payload.duration_months)
|
||||
if computed_end < payload.start_date:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="end_date cannot be earlier than start_date.",
|
||||
)
|
||||
|
||||
warranty = Warranty(
|
||||
asset_id=payload.asset_id,
|
||||
duration_months=payload.duration_months,
|
||||
start_date=payload.start_date,
|
||||
end_date=computed_end,
|
||||
provider_id=payload.provider_id,
|
||||
remarks=payload.remarks.strip() if payload.remarks else None,
|
||||
created_by_id=current_user.id,
|
||||
updated_by_id=current_user.id,
|
||||
)
|
||||
db.add(warranty)
|
||||
db.flush()
|
||||
|
||||
log_audit(
|
||||
db,
|
||||
entity_type="warranty",
|
||||
entity_id=warranty.id,
|
||||
action="create",
|
||||
changes={
|
||||
"asset_id": payload.asset_id,
|
||||
"duration_months": payload.duration_months,
|
||||
"start_date": str(payload.start_date),
|
||||
"end_date": str(computed_end),
|
||||
},
|
||||
user_id=current_user.id,
|
||||
)
|
||||
db.commit()
|
||||
|
||||
loaded = _load_warranty(db, warranty.id)
|
||||
today = effective_today(db)
|
||||
lead_days, red_days = _warranty_lead_settings(db)
|
||||
att_counts = get_attachment_counts(db, "warranty", [warranty.id])
|
||||
return _to_warranty_out(loaded, today, lead_days, red_days, att_counts)
|
||||
|
||||
|
||||
@router.patch("/{warranty_id}", response_model=WarrantyOut)
|
||||
def update_warranty(
|
||||
warranty_id: int,
|
||||
payload: WarrantyUpdate,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.coordinator)),
|
||||
):
|
||||
warranty = db.query(Warranty).filter(Warranty.id == warranty_id).first()
|
||||
if warranty is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Warranty not found.")
|
||||
|
||||
data = payload.model_dump(exclude_unset=True)
|
||||
if "provider_id" in data and data["provider_id"] is not None:
|
||||
if not db.query(Vendor.id).filter(Vendor.id == data["provider_id"]).first():
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Provider vendor not found.")
|
||||
|
||||
new_start = data.get("start_date", warranty.start_date)
|
||||
new_duration = data.get("duration_months", warranty.duration_months)
|
||||
if "end_date" in data and data["end_date"] is not None:
|
||||
new_end = data["end_date"]
|
||||
elif "start_date" in data or "duration_months" in data:
|
||||
new_end = add_months(new_start, new_duration)
|
||||
data["end_date"] = new_end
|
||||
else:
|
||||
new_end = warranty.end_date
|
||||
|
||||
if new_end < new_start:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail="end_date cannot be earlier than start_date.",
|
||||
)
|
||||
|
||||
changes: dict[str, dict[str, object]] = {}
|
||||
for k, v in data.items():
|
||||
if isinstance(v, str):
|
||||
v = v.strip() or None
|
||||
old_val = getattr(warranty, k)
|
||||
if old_val != v:
|
||||
changes[k] = {"from": old_val, "to": v}
|
||||
setattr(warranty, k, v)
|
||||
warranty.updated_by_id = current_user.id
|
||||
|
||||
if changes:
|
||||
log_audit(
|
||||
db,
|
||||
entity_type="warranty",
|
||||
entity_id=warranty.id,
|
||||
action="update",
|
||||
changes=changes,
|
||||
user_id=current_user.id,
|
||||
)
|
||||
db.commit()
|
||||
|
||||
loaded = _load_warranty(db, warranty.id)
|
||||
today = effective_today(db)
|
||||
lead_days, red_days = _warranty_lead_settings(db)
|
||||
att_counts = get_attachment_counts(db, "warranty", [warranty.id])
|
||||
return _to_warranty_out(loaded, today, lead_days, red_days, att_counts)
|
||||
|
||||
|
||||
@router.delete("/{warranty_id}", status_code=status.HTTP_204_NO_CONTENT)
|
||||
def delete_warranty(
|
||||
warranty_id: int,
|
||||
db: Session = Depends(get_db),
|
||||
current_user: User = Depends(require_roles(Role.system_admin, Role.biomedical, Role.coordinator)),
|
||||
):
|
||||
warranty = db.query(Warranty).filter(Warranty.id == warranty_id).first()
|
||||
if warranty is None:
|
||||
raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="Warranty not found.")
|
||||
|
||||
log_audit(
|
||||
db,
|
||||
entity_type="warranty",
|
||||
entity_id=warranty.id,
|
||||
action="delete",
|
||||
changes={"asset_id": warranty.asset_id},
|
||||
user_id=current_user.id,
|
||||
)
|
||||
db.delete(warranty)
|
||||
db.commit()
|
||||
return Response(status_code=status.HTTP_204_NO_CONTENT)
|
||||
Reference in New Issue
Block a user