initial commit
This commit is contained in:
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,719 @@
|
||||
"""
|
||||
AI Narrative generation, strict grounding validation, fallback, and caching.
|
||||
|
||||
All numbers originate exclusively from the deterministic Python metrics engine.
|
||||
Any LLM output is strictly validated for:
|
||||
1. JSON schema shape (headline + up to 6 bullets with metric_ids)
|
||||
2. Every metric_id exists in the evidence list
|
||||
3. Every number in headline/bullets matches a raw or formatted evidence value within 0.5%
|
||||
4. Zero banned words/phrases (approve, approved, guarantee, safe to use, unsafe,
|
||||
purchase immediately, must buy)
|
||||
|
||||
If AI is disabled, unavailable, times out, or fails validation after one retry,
|
||||
a deterministic rule-based narrative is returned cleanly.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
from typing import Any, Optional
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..core.time_utils import utc_now
|
||||
from ..models import AISummary
|
||||
from .ai_metrics import _slug, format_inr
|
||||
from .ai_provider import AIProvider, NoneProvider, ProviderUnavailable, get_ai_provider
|
||||
from .audit import log_audit
|
||||
from .settings_service import get_setting_value
|
||||
|
||||
BANNED_PHRASES: tuple[str, ...] = (
|
||||
"approve",
|
||||
"approved",
|
||||
"guarantee",
|
||||
"safe to use",
|
||||
"unsafe",
|
||||
"purchase immediately",
|
||||
"must buy",
|
||||
)
|
||||
|
||||
ALLOWED_METRIC_KEYS = ("id", "label", "value", "unit", "formatted")
|
||||
ALLOWED_SUGGESTION_KEYS = ("id", "rule", "severity", "asset_codes", "evidence_metric_ids", "action_for_human")
|
||||
|
||||
_EMAIL_RE = re.compile(r"[A-Za-z0-9._%+-]+@[A-Za-z0-9.-]+\.[A-Za-z]{2,}")
|
||||
_ASSET_CODE_RE = re.compile(r"\b[A-Z]{2,10}-[A-Z0-9]{1,10}-\d{2,6}\b")
|
||||
_METRIC_ID_RE = re.compile(r"\bm_[a-zA-Z0-9_]+\b")
|
||||
_RULE_CODE_RE = re.compile(r"\bS[1-8]\b")
|
||||
_NUMBER_RE = re.compile(r"\d+(?:\.\d+)?")
|
||||
|
||||
SYSTEM_PROMPT_TEMPLATE = (
|
||||
"You are writing a short, factual executive note for hospital managers based strictly on "
|
||||
"pre-calculated biomedical equipment metrics.\n"
|
||||
"Rules you MUST follow:\n"
|
||||
"1. Use ONLY the numbers present in the provided JSON evidence. Never calculate new numbers "
|
||||
"or invent figures.\n"
|
||||
"2. Every bullet MUST list the exact `metric_ids` from the JSON that support its numbers.\n"
|
||||
"3. Do NOT recommend purchases, approvals, or clinical safety decisions. Never use the words "
|
||||
"or phrases: approve, approved, guarantee, safe to use, unsafe, purchase immediately, must buy.\n"
|
||||
"4. Do NOT add suggestions beyond the ones provided in the JSON.\n"
|
||||
"5. Answer strictly as a single JSON object matching:\n"
|
||||
'{"headline": "concise 1-sentence summary", "bullets": [{"text": "factual sentence", "metric_ids": ["m_..."]}]}\n'
|
||||
"6. Include between 1 and 6 bullets."
|
||||
)
|
||||
|
||||
|
||||
def _scrub_emails(text: Any) -> str:
|
||||
return _EMAIL_RE.sub("[redacted]", str(text or ""))
|
||||
|
||||
|
||||
def _sanitize_metrics(metrics: list[dict[str, Any]]) -> list[dict[str, Any]]:
|
||||
"""Whitelist strictly allowed evidence keys so PII/free text can never leak."""
|
||||
clean: list[dict[str, Any]] = []
|
||||
for m in metrics or []:
|
||||
if not isinstance(m, dict) or not m.get("id"):
|
||||
continue
|
||||
clean.append(
|
||||
{
|
||||
"id": str(m["id"]),
|
||||
"label": _scrub_emails(m.get("label", "")),
|
||||
"value": m.get("value"),
|
||||
"unit": str(m.get("unit", "")),
|
||||
"formatted": _scrub_emails(m.get("formatted", "")),
|
||||
}
|
||||
)
|
||||
return clean
|
||||
|
||||
|
||||
def _sanitize_suggestions(suggestions: Optional[list[dict[str, Any]]]) -> list[dict[str, Any]]:
|
||||
"""Whitelist strictly structured fields of suggestions (never free-text user input)."""
|
||||
clean: list[dict[str, Any]] = []
|
||||
for s in suggestions or []:
|
||||
if not isinstance(s, dict) or not s.get("id"):
|
||||
continue
|
||||
codes = [str(c) for c in (s.get("asset_codes") or []) if isinstance(c, str)]
|
||||
ev_ids = [str(eid) for eid in (s.get("evidence_metric_ids") or []) if isinstance(eid, str)]
|
||||
clean.append(
|
||||
{
|
||||
"id": str(s["id"]),
|
||||
"rule": str(s.get("rule", "")),
|
||||
"severity": str(s.get("severity", "info")),
|
||||
"asset_codes": codes,
|
||||
"evidence_metric_ids": ev_ids,
|
||||
"action_for_human": _scrub_emails(s.get("action_for_human", "")),
|
||||
}
|
||||
)
|
||||
return clean
|
||||
|
||||
|
||||
def build_prompt(
|
||||
section: str,
|
||||
metrics: list[dict[str, Any]],
|
||||
suggestions: Optional[list[dict[str, Any]]] = None,
|
||||
) -> tuple[str, dict[str, Any]]:
|
||||
"""Build (system_prompt, privacy-safe user_json) for an AI provider."""
|
||||
user_payload = {
|
||||
"section": str(section),
|
||||
"metrics": _sanitize_metrics(metrics),
|
||||
"suggestions": _sanitize_suggestions(suggestions),
|
||||
}
|
||||
return SYSTEM_PROMPT_TEMPLATE, user_payload
|
||||
|
||||
|
||||
def _extract_numbers_from_text(text: str, known_asset_codes: Optional[set[str]] = None) -> list[float]:
|
||||
"""Extract numeric values from text after removing asset codes, metric IDs, ₹, and commas."""
|
||||
s = str(text or "")
|
||||
if known_asset_codes:
|
||||
for code in sorted(known_asset_codes, key=len, reverse=True):
|
||||
if code:
|
||||
s = s.replace(code, " ")
|
||||
s = _ASSET_CODE_RE.sub(" ", s)
|
||||
s = _METRIC_ID_RE.sub(" ", s)
|
||||
s = _RULE_CODE_RE.sub(" ", s)
|
||||
s = s.replace("₹", " ").replace("Rs.", " ").replace("INR", " ")
|
||||
s = re.sub(r"(?<=\d),(?=\d)", "", s)
|
||||
numbers: list[float] = []
|
||||
for tok in _NUMBER_RE.findall(s):
|
||||
try:
|
||||
numbers.append(float(tok))
|
||||
except ValueError:
|
||||
continue
|
||||
return numbers
|
||||
|
||||
|
||||
def _collect_known_numbers(
|
||||
metrics: list[dict[str, Any]],
|
||||
section_data: Optional[dict[str, Any]] = None,
|
||||
) -> list[float]:
|
||||
known: list[float] = []
|
||||
for m in metrics or []:
|
||||
val = m.get("value")
|
||||
if isinstance(val, (int, float)) and not isinstance(val, bool):
|
||||
fval = abs(float(val))
|
||||
known.append(fval)
|
||||
if m.get("unit") == "ratio":
|
||||
known.append(abs(fval * 100.0))
|
||||
fmt = m.get("formatted")
|
||||
if isinstance(fmt, str) and fmt:
|
||||
known.extend(_extract_numbers_from_text(fmt))
|
||||
label = m.get("label")
|
||||
if isinstance(label, str) and label:
|
||||
known.extend(_extract_numbers_from_text(label))
|
||||
|
||||
if isinstance(section_data, dict):
|
||||
settings_used = section_data.get("how_calculated", {}).get("settings_used") or {}
|
||||
for sval in settings_used.values():
|
||||
if isinstance(sval, (int, float)) and not isinstance(sval, bool):
|
||||
known.append(abs(float(sval)))
|
||||
|
||||
return known
|
||||
|
||||
|
||||
def _number_matches(val: float, known_numbers: list[float], rel_tol: float = 0.005) -> bool:
|
||||
for ref in known_numbers:
|
||||
if ref == 0.0:
|
||||
if abs(val) < 1e-6:
|
||||
return True
|
||||
else:
|
||||
if abs(val - ref) <= max(abs(ref) * rel_tol, 1e-6):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _find_banned_phrase(text: str) -> Optional[str]:
|
||||
lower = (text or "").lower()
|
||||
for phrase in BANNED_PHRASES:
|
||||
if re.search(rf"\b{re.escape(phrase)}\b", lower):
|
||||
return phrase
|
||||
return None
|
||||
|
||||
|
||||
def validate_narrative(
|
||||
result: Any,
|
||||
metrics: list[dict[str, Any]],
|
||||
known_asset_codes: Optional[set[str]] = None,
|
||||
section_data: Optional[dict[str, Any]] = None,
|
||||
) -> tuple[bool, Optional[str]]:
|
||||
"""Validate an AI model's JSON response against shape, evidence, numbers, and banned words."""
|
||||
if not isinstance(result, dict):
|
||||
return False, "Model response is not a JSON object."
|
||||
|
||||
headline = result.get("headline")
|
||||
if not isinstance(headline, str) or not headline.strip():
|
||||
return False, "Missing or empty 'headline' field."
|
||||
|
||||
bullets = result.get("bullets")
|
||||
if not isinstance(bullets, list) or len(bullets) == 0 or len(bullets) > 6:
|
||||
return False, "Field 'bullets' must be a list of 1 to 6 items."
|
||||
|
||||
valid_metric_ids = {str(m["id"]) for m in (metrics or []) if isinstance(m, dict) and m.get("id")}
|
||||
known_numbers = _collect_known_numbers(metrics, section_data=section_data)
|
||||
|
||||
# Check banned phrases in headline
|
||||
banned = _find_banned_phrase(headline)
|
||||
if banned:
|
||||
return False, f"Banned phrase found in headline: '{banned}'."
|
||||
|
||||
# Check numbers in headline
|
||||
for num in _extract_numbers_from_text(headline, known_asset_codes):
|
||||
if not _number_matches(num, known_numbers):
|
||||
return False, f"Unverified number in headline: {num:g}."
|
||||
|
||||
for idx, item in enumerate(bullets):
|
||||
if not isinstance(item, dict):
|
||||
return False, f"Bullet {idx + 1} is not an object."
|
||||
text = item.get("text")
|
||||
if not isinstance(text, str) or not text.strip():
|
||||
return False, f"Bullet {idx + 1} has empty 'text'."
|
||||
mids = item.get("metric_ids")
|
||||
if not isinstance(mids, list) or len(mids) == 0 or not all(isinstance(x, str) and x.strip() for x in mids):
|
||||
return False, f"Bullet {idx + 1} must include a non-empty list of 'metric_ids'."
|
||||
|
||||
for mid in mids:
|
||||
if mid not in valid_metric_ids:
|
||||
return False, f"Unknown metric_id referenced: '{mid}'."
|
||||
|
||||
banned = _find_banned_phrase(text)
|
||||
if banned:
|
||||
return False, f"Banned phrase found in bullet {idx + 1}: '{banned}'."
|
||||
|
||||
for num in _extract_numbers_from_text(text, known_asset_codes):
|
||||
if not _number_matches(num, known_numbers):
|
||||
return False, f"Unverified number in bullet {idx + 1}: {num:g}."
|
||||
|
||||
return True, None
|
||||
|
||||
|
||||
def rule_based_narrative(
|
||||
section: str,
|
||||
metrics: list[dict[str, Any]],
|
||||
suggestions: Optional[list[dict[str, Any]]] = None,
|
||||
section_data: Optional[dict[str, Any]] = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Build deterministic narrative headline and bullets strictly from computed evidence."""
|
||||
by_id = {m["id"]: m for m in (metrics or []) if isinstance(m, dict) and m.get("id")}
|
||||
bullets: list[dict[str, Any]] = []
|
||||
|
||||
def _has(*ids: str) -> bool:
|
||||
return all(i in by_id for i in ids)
|
||||
|
||||
def _fmt(mid: str) -> str:
|
||||
return str(by_id[mid]["formatted"])
|
||||
|
||||
sec = (section or "summary").strip().lower()
|
||||
|
||||
if sec == "comparison":
|
||||
horizon_m = by_id.get("m_cmp_horizon_years")
|
||||
count_m = by_id.get("m_cmp_latest_count")
|
||||
horizon_val = horizon_m["value"] if horizon_m else 5
|
||||
count_val = count_m["value"] if count_m else 0
|
||||
|
||||
headline = (
|
||||
f"Evaluated {count_val} latest equipment items over a {horizon_val}-year horizon "
|
||||
f"across in-house, outsourced, and rent scenarios."
|
||||
)
|
||||
if _has("m_cmp_inhouse_wins", "m_cmp_outsourced_wins", "m_cmp_rent_wins"):
|
||||
bullets.append(
|
||||
{
|
||||
"text": (
|
||||
f"Lowest-cost scenario split across evaluated equipment: "
|
||||
f"{_fmt('m_cmp_inhouse_wins')} in-house, "
|
||||
f"{_fmt('m_cmp_outsourced_wins')} outsourced (AMC/CMC), and "
|
||||
f"{_fmt('m_cmp_rent_wins')} rent."
|
||||
),
|
||||
"metric_ids": ["m_cmp_inhouse_wins", "m_cmp_outsourced_wins", "m_cmp_rent_wins"],
|
||||
}
|
||||
)
|
||||
rows = (section_data or {}).get("rows") or []
|
||||
for row in rows:
|
||||
if len(bullets) >= 6:
|
||||
break
|
||||
code = row.get("asset_code")
|
||||
lowest_label = row.get("lowest_scenario_label")
|
||||
lowest_cost = row.get("lowest_cost")
|
||||
diff = row.get("savings_vs_next")
|
||||
if not code or lowest_cost is None:
|
||||
continue
|
||||
slug = _slug(code)
|
||||
low_id = f"m_cmp_lowest_{slug}"
|
||||
diff_id = f"m_cmp_diff_{slug}"
|
||||
if _has(low_id, diff_id) and diff is not None:
|
||||
mids = [low_id, diff_id]
|
||||
if "m_cmp_horizon_years" in by_id:
|
||||
mids.insert(0, "m_cmp_horizon_years")
|
||||
bullets.append(
|
||||
{
|
||||
"text": (
|
||||
f"Lowest estimated {horizon_val}-year cost for {code} is "
|
||||
f"{lowest_label} at {_fmt(low_id)}, {_fmt(diff_id)} below the next option."
|
||||
),
|
||||
"metric_ids": mids,
|
||||
}
|
||||
)
|
||||
elif _has(low_id):
|
||||
mids = [low_id]
|
||||
if "m_cmp_horizon_years" in by_id:
|
||||
mids.insert(0, "m_cmp_horizon_years")
|
||||
bullets.append(
|
||||
{
|
||||
"text": (
|
||||
f"Estimated {horizon_val}-year cost for {code} under {lowest_label} is "
|
||||
f"{_fmt(low_id)} (other scenarios lack complete inputs)."
|
||||
),
|
||||
"metric_ids": mids,
|
||||
}
|
||||
)
|
||||
|
||||
elif sec == "depreciation":
|
||||
headline = "Depreciated book value and cumulative maintenance cost summary for assets in scope."
|
||||
if _has("m_dep_total_purchase_value", "m_dep_total_book_value"):
|
||||
headline = (
|
||||
f"Owned assets hold a current book value of {_fmt('m_dep_total_book_value')} "
|
||||
f"against {_fmt('m_dep_total_purchase_value')} in purchase value."
|
||||
)
|
||||
bullets.append(
|
||||
{
|
||||
"text": (
|
||||
f"Total purchase value is {_fmt('m_dep_total_purchase_value')}, with "
|
||||
f"{_fmt('m_dep_total_book_value')} remaining book value and "
|
||||
f"{_fmt('m_dep_total_accumulated')} accumulated depreciation."
|
||||
if "m_dep_total_accumulated" in by_id
|
||||
else f"Total purchase value is {_fmt('m_dep_total_purchase_value')} with {_fmt('m_dep_total_book_value')} current book value."
|
||||
),
|
||||
"metric_ids": [
|
||||
mid
|
||||
for mid in ("m_dep_total_purchase_value", "m_dep_total_book_value", "m_dep_total_accumulated")
|
||||
if mid in by_id
|
||||
],
|
||||
}
|
||||
)
|
||||
if _has("m_dep_total_maintenance"):
|
||||
bullets.append(
|
||||
{
|
||||
"text": f"Cumulative maintenance expenditure to date totals {_fmt('m_dep_total_maintenance')}.",
|
||||
"metric_ids": ["m_dep_total_maintenance"],
|
||||
}
|
||||
)
|
||||
if _has("m_dep_review_flag_count", "m_dep_fully_depreciated_count"):
|
||||
bullets.append(
|
||||
{
|
||||
"text": (
|
||||
f"{_fmt('m_dep_review_flag_count')} asset(s) meet or exceed the replacement review "
|
||||
f"maintenance ratio, and {_fmt('m_dep_fully_depreciated_count')} asset(s) are fully depreciated."
|
||||
),
|
||||
"metric_ids": ["m_dep_review_flag_count", "m_dep_fully_depreciated_count"],
|
||||
}
|
||||
)
|
||||
if _has("m_dep_excluded_count") and by_id["m_dep_excluded_count"]["value"]:
|
||||
bullets.append(
|
||||
{
|
||||
"text": (
|
||||
f"{_fmt('m_dep_excluded_count')} asset(s) were excluded from depreciation totals "
|
||||
f"(rented equipment or missing valuation/date inputs)."
|
||||
),
|
||||
"metric_ids": ["m_dep_excluded_count"],
|
||||
}
|
||||
)
|
||||
|
||||
elif sec == "efficiency":
|
||||
headline = "Equipment efficiency combines uptime, PM compliance, SLA response, and repeat-free reliability."
|
||||
if _has("m_eff_score_overall", "m_eff_avg_uptime"):
|
||||
headline = (
|
||||
f"Overall efficiency score is {_fmt('m_eff_score_overall')} with "
|
||||
f"{_fmt('m_eff_avg_uptime')} average uptime."
|
||||
)
|
||||
bullets.append(
|
||||
{
|
||||
"text": (
|
||||
f"Weighted efficiency score is {_fmt('m_eff_score_overall')} across operational assets, "
|
||||
f"driven by {_fmt('m_eff_avg_uptime')} average uptime."
|
||||
),
|
||||
"metric_ids": ["m_eff_score_overall", "m_eff_avg_uptime"],
|
||||
}
|
||||
)
|
||||
if _has("m_eff_pm_compliance"):
|
||||
bullets.append(
|
||||
{
|
||||
"text": f"On-time preventive maintenance compliance stands at {_fmt('m_eff_pm_compliance')}.",
|
||||
"metric_ids": ["m_eff_pm_compliance"],
|
||||
}
|
||||
)
|
||||
if _has("m_eff_mttr") and by_id["m_eff_mttr"]["value"] is not None:
|
||||
mids = ["m_eff_mttr"]
|
||||
extra = ""
|
||||
if _has("m_eff_mtbf") and by_id["m_eff_mtbf"]["value"] is not None:
|
||||
mids.append("m_eff_mtbf")
|
||||
extra = f" and mean time between failures (MTBF) is {_fmt('m_eff_mtbf')}"
|
||||
bullets.append(
|
||||
{
|
||||
"text": f"Mean time to repair (MTTR) is {_fmt('m_eff_mttr')}{extra}.",
|
||||
"metric_ids": mids,
|
||||
}
|
||||
)
|
||||
elif _has("m_eff_mtbf"):
|
||||
bullets.append(
|
||||
{
|
||||
"text": f"Mean time between failures (MTBF) status: {_fmt('m_eff_mtbf')}.",
|
||||
"metric_ids": ["m_eff_mtbf"],
|
||||
}
|
||||
)
|
||||
|
||||
elif sec in ("breakdown_frequency", "breakdown-frequency"):
|
||||
headline = "Breakdown frequency and repeat-failure summary across equipment in scope."
|
||||
if _has("m_bf_total_breakdowns", "m_bf_assets_in_scope", "m_bf_avg_per_equipment"):
|
||||
headline = (
|
||||
f"{_fmt('m_bf_total_breakdowns')} breakdowns logged across {_fmt('m_bf_assets_in_scope')} "
|
||||
f"assets (average {_fmt('m_bf_avg_per_equipment')} per equipment)."
|
||||
)
|
||||
bullets.append(
|
||||
{
|
||||
"text": (
|
||||
f"A total of {_fmt('m_bf_total_breakdowns')} breakdown complaints were recorded across "
|
||||
f"{_fmt('m_bf_assets_in_scope')} assets, averaging {_fmt('m_bf_avg_per_equipment')} per equipment."
|
||||
),
|
||||
"metric_ids": ["m_bf_total_breakdowns", "m_bf_assets_in_scope", "m_bf_avg_per_equipment"],
|
||||
}
|
||||
)
|
||||
if _has("m_bf_repeat_failure_assets"):
|
||||
bullets.append(
|
||||
{
|
||||
"text": f"{_fmt('m_bf_repeat_failure_assets')} asset(s) are currently flagged for repeat failures.",
|
||||
"metric_ids": ["m_bf_repeat_failure_assets"],
|
||||
}
|
||||
)
|
||||
rows = (section_data or {}).get("rows") or []
|
||||
if rows and rows[0].get("breakdown_count", 0) > 0:
|
||||
top = rows[0]
|
||||
mid = f"m_bf_count_{_slug(top['asset_code'])}"
|
||||
if mid in by_id:
|
||||
bullets.append(
|
||||
{
|
||||
"text": (
|
||||
f"Highest breakdown volume in the period was on {top['asset_code']} "
|
||||
f"({top.get('asset_name', '')}) with {_fmt(mid)} complaint(s)."
|
||||
),
|
||||
"metric_ids": [mid],
|
||||
}
|
||||
)
|
||||
|
||||
else:
|
||||
# Whole-report executive summary ("summary")
|
||||
headline = "Executive summary of equipment cost comparison, depreciation, efficiency, and breakdown frequency."
|
||||
if _has("m_cmp_latest_count", "m_cmp_horizon_years"):
|
||||
bullets.append(
|
||||
{
|
||||
"text": (
|
||||
f"Cost comparison evaluated {_fmt('m_cmp_latest_count')} latest assets over "
|
||||
f"{_fmt('m_cmp_horizon_years')}."
|
||||
),
|
||||
"metric_ids": ["m_cmp_latest_count", "m_cmp_horizon_years"],
|
||||
}
|
||||
)
|
||||
if _has("m_dep_total_book_value", "m_dep_total_maintenance"):
|
||||
bullets.append(
|
||||
{
|
||||
"text": (
|
||||
f"Owned equipment book value is {_fmt('m_dep_total_book_value')} with "
|
||||
f"{_fmt('m_dep_total_maintenance')} in cumulative maintenance costs."
|
||||
),
|
||||
"metric_ids": ["m_dep_total_book_value", "m_dep_total_maintenance"],
|
||||
}
|
||||
)
|
||||
if _has("m_eff_score_overall", "m_eff_avg_uptime"):
|
||||
bullets.append(
|
||||
{
|
||||
"text": (
|
||||
f"Overall operational efficiency score is {_fmt('m_eff_score_overall')} "
|
||||
f"with {_fmt('m_eff_avg_uptime')} average uptime."
|
||||
),
|
||||
"metric_ids": ["m_eff_score_overall", "m_eff_avg_uptime"],
|
||||
}
|
||||
)
|
||||
if _has("m_bf_total_breakdowns", "m_bf_repeat_failure_assets"):
|
||||
bullets.append(
|
||||
{
|
||||
"text": (
|
||||
f"{_fmt('m_bf_total_breakdowns')} breakdowns recorded in period, with "
|
||||
f"{_fmt('m_bf_repeat_failure_assets')} repeat-failure asset(s)."
|
||||
),
|
||||
"metric_ids": ["m_bf_total_breakdowns", "m_bf_repeat_failure_assets"],
|
||||
}
|
||||
)
|
||||
if _has("m_sug_total_count"):
|
||||
bullets.append(
|
||||
{
|
||||
"text": (
|
||||
f"{_fmt('m_sug_total_count')} advisory suggestion(s) generated for human review."
|
||||
),
|
||||
"metric_ids": ["m_sug_total_count"],
|
||||
}
|
||||
)
|
||||
|
||||
# Fallback bullet if metrics were minimal or custom
|
||||
if not bullets:
|
||||
for m in (metrics or [])[:4]:
|
||||
bullets.append(
|
||||
{
|
||||
"text": f"{m['label']}: {m['formatted']}.",
|
||||
"metric_ids": [m["id"]],
|
||||
}
|
||||
)
|
||||
if not bullets:
|
||||
bullets.append(
|
||||
{
|
||||
"text": "Add cost and operational details on asset records to generate metrics for this section.",
|
||||
"metric_ids": [],
|
||||
}
|
||||
)
|
||||
|
||||
return {
|
||||
"headline": headline,
|
||||
"bullets": bullets[:6],
|
||||
}
|
||||
|
||||
|
||||
def _sha256_canonical(obj: Any) -> str:
|
||||
encoded = json.dumps(obj, sort_keys=True, default=str, ensure_ascii=False).encode("utf-8")
|
||||
return hashlib.sha256(encoded).hexdigest()
|
||||
|
||||
|
||||
def get_or_generate_narrative(
|
||||
db: Session,
|
||||
section: str,
|
||||
filters_dict: dict[str, Any],
|
||||
metrics: list[dict[str, Any]],
|
||||
suggestions: Optional[list[dict[str, Any]]] = None,
|
||||
*,
|
||||
section_data: Optional[dict[str, Any]] = None,
|
||||
user_id: Optional[int] = None,
|
||||
force_regenerate: bool = False,
|
||||
provider_override: Optional[AIProvider] = None,
|
||||
ai_enabled_override: Optional[bool] = None,
|
||||
) -> dict[str, Any]:
|
||||
"""
|
||||
Return a cached or freshly generated narrative for `section`.
|
||||
Never raises on provider errors; always returns a complete narrative dict.
|
||||
"""
|
||||
provider = provider_override or get_ai_provider()
|
||||
ai_enabled = (
|
||||
bool(ai_enabled_override)
|
||||
if ai_enabled_override is not None
|
||||
else bool(get_setting_value(db, "ai_enabled", True))
|
||||
)
|
||||
use_ai = ai_enabled and not isinstance(provider, NoneProvider)
|
||||
|
||||
clean_metrics = _sanitize_metrics(metrics)
|
||||
clean_suggestions = _sanitize_suggestions(suggestions)
|
||||
|
||||
cache_filters = {
|
||||
**(filters_dict or {}),
|
||||
"_use_ai": use_ai,
|
||||
"_provider": provider.provider_name if use_ai else "none",
|
||||
"_model": provider.model_name if use_ai else "",
|
||||
}
|
||||
filters_hash = _sha256_canonical(cache_filters)
|
||||
data_hash = _sha256_canonical({"metrics": clean_metrics, "suggestions": clean_suggestions})
|
||||
|
||||
if not force_regenerate:
|
||||
cached = (
|
||||
db.query(AISummary)
|
||||
.filter(
|
||||
AISummary.section == section,
|
||||
AISummary.filters_hash == filters_hash,
|
||||
AISummary.data_hash == data_hash,
|
||||
AISummary.validated == True,
|
||||
)
|
||||
.order_by(AISummary.id.desc())
|
||||
.first()
|
||||
)
|
||||
if cached is not None:
|
||||
try:
|
||||
cached_data = json.loads(cached.payload_json)
|
||||
if not cached_data.get("failure_reason"):
|
||||
return cached_data
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
known_codes: set[str] = set()
|
||||
for s in clean_suggestions:
|
||||
known_codes.update(s.get("asset_codes") or [])
|
||||
for r in (section_data or {}).get("rows") or []:
|
||||
if isinstance(r, dict) and r.get("asset_code"):
|
||||
known_codes.add(str(r["asset_code"]))
|
||||
|
||||
source = "rule_based"
|
||||
model_used: Optional[str] = None
|
||||
validated = True
|
||||
failure_reason: Optional[str] = None
|
||||
narrative_body: Optional[dict[str, Any]] = None
|
||||
|
||||
if use_ai:
|
||||
model_used = provider.model_name or provider.provider_name
|
||||
sys_prompt, user_payload = build_prompt(section, clean_metrics, clean_suggestions)
|
||||
last_error: Optional[str] = None
|
||||
for attempt in range(2):
|
||||
prompt_for_attempt = sys_prompt
|
||||
if attempt == 1 and last_error:
|
||||
prompt_for_attempt = (
|
||||
f"{sys_prompt}\n\n"
|
||||
f"Your previous answer was rejected for this reason: {last_error}\n"
|
||||
"Fix this issue and return strictly valid JSON."
|
||||
)
|
||||
try:
|
||||
raw_resp = provider.generate_json(prompt_for_attempt, user_payload)
|
||||
except ProviderUnavailable as exc:
|
||||
last_error = str(exc)
|
||||
break
|
||||
except Exception as exc:
|
||||
last_error = f"Invalid model output: {exc}"
|
||||
if attempt == 0:
|
||||
continue
|
||||
break
|
||||
|
||||
ok, reason = validate_narrative(
|
||||
raw_resp,
|
||||
clean_metrics,
|
||||
known_asset_codes=known_codes,
|
||||
section_data=section_data,
|
||||
)
|
||||
if ok:
|
||||
narrative_body = {
|
||||
"headline": raw_resp["headline"].strip(),
|
||||
"bullets": [
|
||||
{
|
||||
"text": b["text"].strip(),
|
||||
"metric_ids": list(b["metric_ids"]),
|
||||
}
|
||||
for b in raw_resp["bullets"]
|
||||
],
|
||||
}
|
||||
source = "ai"
|
||||
validated = True
|
||||
failure_reason = None
|
||||
break
|
||||
else:
|
||||
last_error = reason or "Narrative failed validation."
|
||||
|
||||
if narrative_body is None:
|
||||
narrative_body = rule_based_narrative(
|
||||
section,
|
||||
clean_metrics,
|
||||
clean_suggestions,
|
||||
section_data=section_data,
|
||||
)
|
||||
source = "rule_based"
|
||||
validated = False
|
||||
failure_reason = last_error or "AI provider fallback triggered."
|
||||
else:
|
||||
narrative_body = rule_based_narrative(
|
||||
section,
|
||||
clean_metrics,
|
||||
clean_suggestions,
|
||||
section_data=section_data,
|
||||
)
|
||||
source = "rule_based"
|
||||
model_used = None
|
||||
validated = True
|
||||
failure_reason = None
|
||||
|
||||
generated_at = utc_now().isoformat()
|
||||
payload = {
|
||||
"source": source,
|
||||
"model": model_used,
|
||||
"validated": validated,
|
||||
"failure_reason": failure_reason,
|
||||
"generated_at": generated_at,
|
||||
"headline": narrative_body["headline"],
|
||||
"bullets": narrative_body["bullets"],
|
||||
}
|
||||
|
||||
row = AISummary(
|
||||
section=section,
|
||||
filters_hash=filters_hash,
|
||||
data_hash=data_hash,
|
||||
source=source,
|
||||
model=model_used,
|
||||
validated=validated,
|
||||
payload_json=json.dumps(payload, ensure_ascii=False),
|
||||
created_at=utc_now(),
|
||||
created_by_id=user_id,
|
||||
)
|
||||
db.add(row)
|
||||
db.flush()
|
||||
log_audit(
|
||||
db,
|
||||
entity_type="ai_summary",
|
||||
entity_id=row.id,
|
||||
action="regenerated" if force_regenerate else "generated",
|
||||
changes={
|
||||
"section": section,
|
||||
"source": source,
|
||||
"model": model_used,
|
||||
"validated": validated,
|
||||
"failure_reason": failure_reason,
|
||||
},
|
||||
user_id=user_id,
|
||||
)
|
||||
db.commit()
|
||||
return payload
|
||||
|
||||
@@ -0,0 +1,218 @@
|
||||
"""
|
||||
Pluggable local AI provider layer for AI Reports.
|
||||
|
||||
Supports:
|
||||
- none (default): deterministic rule-based summaries only; raises ProviderUnavailable.
|
||||
- ollama: POST {base}/api/chat with format="json", stream=False, temperature=0.1.
|
||||
- openai_compatible: POST {base}/v1/chat/completions with response_format={"type": "json_object"}, temperature=0.1.
|
||||
|
||||
No hosted cloud provider is configured or required. Prompts and responses are never
|
||||
logged at INFO level.
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from abc import ABC, abstractmethod
|
||||
import json
|
||||
from typing import Any, Optional
|
||||
import httpx
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..core.config import Settings, settings as app_settings
|
||||
from .settings_service import get_setting_value
|
||||
|
||||
|
||||
class ProviderUnavailable(Exception):
|
||||
"""Raised when no AI provider is enabled or the provider cannot be reached."""
|
||||
|
||||
|
||||
class AIProvider(ABC):
|
||||
provider_name: str = "none"
|
||||
model_name: str = ""
|
||||
|
||||
@abstractmethod
|
||||
def generate_json(self, system_prompt: str, user_json: dict[str, Any]) -> dict[str, Any]:
|
||||
"""Call the model and return a parsed JSON object."""
|
||||
|
||||
@abstractmethod
|
||||
def check_reachable(self, timeout: float = 2.5) -> bool:
|
||||
"""Quick reachability check that never blocks longer than `timeout` seconds."""
|
||||
|
||||
|
||||
class NoneProvider(AIProvider):
|
||||
provider_name = "none"
|
||||
model_name = ""
|
||||
|
||||
def generate_json(self, system_prompt: str, user_json: dict[str, Any]) -> dict[str, Any]:
|
||||
raise ProviderUnavailable("AI provider is disabled (AI_PROVIDER=none).")
|
||||
|
||||
def check_reachable(self, timeout: float = 2.5) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
class OllamaProvider(AIProvider):
|
||||
provider_name = "ollama"
|
||||
|
||||
def __init__(self, base_url: str, model: str, timeout_seconds: int = 300) -> None:
|
||||
self.base_url = (base_url or "http://localhost:11434").rstrip("/")
|
||||
self.model_name = (model or "").strip()
|
||||
self.timeout_seconds = max(1, int(timeout_seconds or 300))
|
||||
|
||||
def generate_json(self, system_prompt: str, user_json: dict[str, Any]) -> dict[str, Any]:
|
||||
if not self.model_name:
|
||||
raise ProviderUnavailable("AI_MODEL is not configured for Ollama.")
|
||||
url = f"{self.base_url}/api/chat"
|
||||
payload = {
|
||||
"model": self.model_name,
|
||||
"messages": [
|
||||
{"role": "system", "content": system_prompt},
|
||||
{"role": "user", "content": json.dumps(user_json, ensure_ascii=False)},
|
||||
],
|
||||
"format": "json",
|
||||
"stream": False,
|
||||
"options": {"temperature": 0.1},
|
||||
}
|
||||
try:
|
||||
with httpx.Client(timeout=float(self.timeout_seconds)) as client:
|
||||
resp = client.post(url, json=payload)
|
||||
resp.raise_for_status()
|
||||
body = resp.json()
|
||||
except httpx.TimeoutException as exc:
|
||||
raise ProviderUnavailable(f"AI engine request timed out after {self.timeout_seconds}s.") from exc
|
||||
except httpx.HTTPError as exc:
|
||||
raise ProviderUnavailable(f"AI engine HTTP error: {exc.__class__.__name__}") from exc
|
||||
except ValueError as exc:
|
||||
raise ValueError("AI engine returned invalid JSON envelope.") from exc
|
||||
|
||||
content = (body.get("message") or {}).get("content")
|
||||
if isinstance(content, dict):
|
||||
return content
|
||||
if not isinstance(content, str) or not content.strip():
|
||||
raise ValueError("Ollama returned empty message content.")
|
||||
parsed = json.loads(content)
|
||||
if not isinstance(parsed, dict):
|
||||
raise ValueError("Ollama JSON response must be an object.")
|
||||
return parsed
|
||||
|
||||
def check_reachable(self, timeout: float = 2.5) -> bool:
|
||||
cap = min(float(timeout), 3.0)
|
||||
url = f"{self.base_url}/api/tags"
|
||||
try:
|
||||
with httpx.Client(timeout=cap) as client:
|
||||
resp = client.get(url)
|
||||
return resp.status_code == 200
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
class OpenAICompatibleProvider(AIProvider):
|
||||
provider_name = "openai_compatible"
|
||||
|
||||
def __init__(
|
||||
self,
|
||||
base_url: str,
|
||||
model: str,
|
||||
api_key: str = "",
|
||||
timeout_seconds: int = 25,
|
||||
) -> None:
|
||||
raw = (base_url or "http://localhost:8001").rstrip("/")
|
||||
self.base_url = raw[:-3] if raw.endswith("/v1") else raw
|
||||
self.model_name = (model or "").strip()
|
||||
self.api_key = (api_key or "").strip()
|
||||
self.timeout_seconds = max(1, int(timeout_seconds or 25))
|
||||
|
||||
def _headers(self) -> dict[str, str]:
|
||||
headers = {"Content-Type": "application/json"}
|
||||
if self.api_key:
|
||||
headers["Authorization"] = f"Bearer {self.api_key}"
|
||||
return headers
|
||||
|
||||
def generate_json(self, system_prompt: str, user_json: dict[str, Any]) -> dict[str, Any]:
|
||||
if not self.model_name:
|
||||
raise ProviderUnavailable("AI_MODEL is not configured for OpenAI-compatible provider.")
|
||||
url = f"{self.base_url}/v1/chat/completions"
|
||||
payload = {
|
||||
"model": self.model_name,
|
||||
"messages": [
|
||||
{"role": "system", "content": system_prompt},
|
||||
{"role": "user", "content": json.dumps(user_json, ensure_ascii=False)},
|
||||
],
|
||||
"response_format": {"type": "json_object"},
|
||||
"temperature": 0.1,
|
||||
}
|
||||
try:
|
||||
with httpx.Client(timeout=float(self.timeout_seconds)) as client:
|
||||
resp = client.post(url, headers=self._headers(), json=payload)
|
||||
resp.raise_for_status()
|
||||
body = resp.json()
|
||||
except httpx.TimeoutException as exc:
|
||||
raise ProviderUnavailable(
|
||||
f"OpenAI-compatible request timed out after {self.timeout_seconds}s."
|
||||
) from exc
|
||||
except httpx.HTTPError as exc:
|
||||
raise ProviderUnavailable(f"OpenAI-compatible HTTP error: {exc.__class__.__name__}") from exc
|
||||
except ValueError as exc:
|
||||
raise ValueError("OpenAI-compatible server returned invalid JSON envelope.") from exc
|
||||
|
||||
choices = body.get("choices") or []
|
||||
if not choices or not isinstance(choices, list):
|
||||
raise ValueError("OpenAI-compatible response contained no choices.")
|
||||
content = (choices[0].get("message") or {}).get("content")
|
||||
if isinstance(content, dict):
|
||||
return content
|
||||
if not isinstance(content, str) or not content.strip():
|
||||
raise ValueError("OpenAI-compatible response contained empty content.")
|
||||
parsed = json.loads(content)
|
||||
if not isinstance(parsed, dict):
|
||||
raise ValueError("OpenAI-compatible JSON response must be an object.")
|
||||
return parsed
|
||||
|
||||
def check_reachable(self, timeout: float = 2.5) -> bool:
|
||||
cap = min(float(timeout), 3.0)
|
||||
url = f"{self.base_url}/v1/models"
|
||||
try:
|
||||
with httpx.Client(timeout=cap) as client:
|
||||
resp = client.get(url, headers=self._headers())
|
||||
return resp.status_code == 200
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def get_ai_provider(cfg: Optional[Settings] = None) -> AIProvider:
|
||||
conf = cfg or app_settings
|
||||
name = (conf.AI_PROVIDER or "none").strip().lower()
|
||||
if name == "ollama":
|
||||
return OllamaProvider(
|
||||
base_url=conf.AI_BASE_URL,
|
||||
model=conf.AI_MODEL,
|
||||
timeout_seconds=conf.AI_TIMEOUT_SECONDS,
|
||||
)
|
||||
if name == "openai_compatible":
|
||||
return OpenAICompatibleProvider(
|
||||
base_url=conf.AI_BASE_URL,
|
||||
model=conf.AI_MODEL,
|
||||
api_key=conf.AI_API_KEY,
|
||||
timeout_seconds=conf.AI_TIMEOUT_SECONDS,
|
||||
)
|
||||
return NoneProvider()
|
||||
|
||||
|
||||
def get_ai_status(
|
||||
db: Session,
|
||||
cfg: Optional[Settings] = None,
|
||||
provider_override: Optional[AIProvider] = None,
|
||||
) -> dict[str, Any]:
|
||||
conf = cfg or app_settings
|
||||
provider = provider_override or get_ai_provider(conf)
|
||||
ai_enabled_setting = bool(get_setting_value(db, "ai_enabled", False))
|
||||
provider_name = provider.provider_name
|
||||
model_name = provider.model_name or ""
|
||||
reachable = provider.check_reachable(timeout=2.5) if provider_name != "none" else False
|
||||
return {
|
||||
"enabled": ai_enabled_setting and provider_name != "none",
|
||||
"ai_enabled_setting": ai_enabled_setting,
|
||||
"provider": provider_name,
|
||||
"model": model_name,
|
||||
"reachable": reachable,
|
||||
}
|
||||
|
||||
@@ -0,0 +1,434 @@
|
||||
"""
|
||||
Rule-based Suggestions Engine (S1-S8) for AI Reports.
|
||||
|
||||
Pure Python deterministic rules with zero LLM involvement. Every suggestion links
|
||||
to concrete evidence metric IDs, uses neutral advisory language (never 'approve',
|
||||
'safe', 'unsafe', 'must buy'), and ends its action text with 'Needs a human decision.'
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import date
|
||||
from typing import Any, Optional
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..models import User
|
||||
from .ai_metrics import (
|
||||
_slug,
|
||||
_to_date,
|
||||
compute_breakdown_frequency_from_dataset,
|
||||
compute_comparison_from_dataset,
|
||||
compute_depreciation_from_dataset,
|
||||
compute_efficiency_from_dataset,
|
||||
format_inr,
|
||||
load_ai_dataset,
|
||||
make_metric,
|
||||
scenario_comparison,
|
||||
)
|
||||
|
||||
SEVERITY_RANK: dict[str, int] = {"red": 0, "yellow": 1, "info": 2}
|
||||
|
||||
SCENARIO_DISPLAY_NAMES: dict[str, str] = {
|
||||
"in_house": "Buy + In-House Maintenance",
|
||||
"outsourced": "Buy + Outsourced Contract (AMC/CMC)",
|
||||
"rent": "Rent",
|
||||
}
|
||||
|
||||
|
||||
def generate_suggestions(
|
||||
dataset: dict[str, Any],
|
||||
*,
|
||||
comparison: Optional[dict[str, Any]] = None,
|
||||
depreciation_data: Optional[dict[str, Any]] = None,
|
||||
efficiency_data: Optional[dict[str, Any]] = None,
|
||||
breakdown_data: Optional[dict[str, Any]] = None,
|
||||
) -> dict[str, Any]:
|
||||
"""Generate sorted S1-S8 suggestions and their complete referenced evidence list."""
|
||||
cfg = dataset["settings"]
|
||||
today: date = dataset["today"]
|
||||
contract_lead_days = int(cfg.get("contract_expiry_alert_days", 30))
|
||||
horizon = int(cfg.get("comparison_horizon_years", 5))
|
||||
review_threshold = float(cfg.get("replacement_review_ratio", 0.4))
|
||||
|
||||
cmp_data = comparison or compute_comparison_from_dataset(dataset)
|
||||
dep_data = depreciation_data or compute_depreciation_from_dataset(dataset)
|
||||
eff_data = efficiency_data or compute_efficiency_from_dataset(dataset)
|
||||
bf_data = breakdown_data or compute_breakdown_frequency_from_dataset(dataset)
|
||||
|
||||
evidence_by_id: dict[str, dict[str, Any]] = {}
|
||||
for sec in (cmp_data, dep_data, eff_data, bf_data):
|
||||
for m in sec.get("metrics", []):
|
||||
evidence_by_id[m["id"]] = m
|
||||
|
||||
def _add_ev(metric: dict[str, Any]) -> str:
|
||||
evidence_by_id[metric["id"]] = metric
|
||||
return metric["id"]
|
||||
|
||||
dep_by_asset = {int(r["asset_id"]): r for r in dep_data.get("rows", [])}
|
||||
eff_by_asset = {int(r["asset_id"]): r for r in eff_data.get("per_asset", [])}
|
||||
bf_by_asset = {int(r["asset_id"]): r for r in bf_data.get("per_asset", [])}
|
||||
cov_by_asset = dataset.get("coverage_by_asset", {})
|
||||
|
||||
suggestions: list[dict[str, Any]] = []
|
||||
|
||||
for a in dataset.get("assets", []):
|
||||
aid = int(a["id"])
|
||||
code = a["asset_code"]
|
||||
name = a["name"]
|
||||
slug = _slug(code)
|
||||
|
||||
bf_row = bf_by_asset.get(aid, {})
|
||||
dep_row = dep_by_asset.get(aid, {})
|
||||
eff_row = eff_by_asset.get(aid, {})
|
||||
cov = cov_by_asset.get(aid, {})
|
||||
|
||||
period_b = int(bf_row.get("breakdown_count", 0))
|
||||
repeat_cnt_val = int(bf_row.get("repeat_window_count", 0))
|
||||
is_repeat = bool(bf_row.get("repeat_failure", False))
|
||||
|
||||
# --- S1: Repeat failure ---
|
||||
if is_repeat:
|
||||
sev = "red" if repeat_cnt_val >= 4 else "yellow"
|
||||
ev_id = _add_ev(
|
||||
make_metric(
|
||||
f"m_bf_repeat_window_{slug}",
|
||||
f"Breakdowns in Last {cfg.get('repeat_failure_days', 90)}d ({code})",
|
||||
repeat_cnt_val,
|
||||
"count",
|
||||
)
|
||||
)
|
||||
suggestions.append(
|
||||
{
|
||||
"id": f"S1_{slug}",
|
||||
"rule": "S1",
|
||||
"severity": sev,
|
||||
"title": f"Repeat failure on {code} ({name})",
|
||||
"detail": (
|
||||
f"{code} recorded {repeat_cnt_val} breakdowns within the last "
|
||||
f"{cfg.get('repeat_failure_days', 90)} days."
|
||||
),
|
||||
"asset_codes": [code],
|
||||
"evidence_metric_ids": [ev_id],
|
||||
"action_for_human": "Review root cause and escalate to the vendor. Needs a human decision.",
|
||||
}
|
||||
)
|
||||
|
||||
# --- S2: Out-of-contract with >= 2 breakdowns in period ---
|
||||
cov_tag = cov.get("tag", "out_of_contract")
|
||||
if cov_tag == "out_of_contract" and period_b >= 2:
|
||||
ev_b = _add_ev(
|
||||
make_metric(
|
||||
f"m_bf_count_{slug}",
|
||||
f"Breakdowns in Period ({code})",
|
||||
period_b,
|
||||
"count",
|
||||
)
|
||||
)
|
||||
ev_cov = _add_ev(
|
||||
make_metric(
|
||||
f"m_cov_tag_{slug}",
|
||||
f"Current Coverage ({code})",
|
||||
"out_of_contract",
|
||||
"status",
|
||||
"Out of Contract",
|
||||
)
|
||||
)
|
||||
suggestions.append(
|
||||
{
|
||||
"id": f"S2_{slug}",
|
||||
"rule": "S2",
|
||||
"severity": "yellow",
|
||||
"title": f"Out-of-contract equipment with recurring breakdowns: {code}",
|
||||
"detail": (
|
||||
f"{code} ({name}) has no active warranty or AMC/CMC contract and logged "
|
||||
f"{period_b} breakdowns in the selected period."
|
||||
),
|
||||
"asset_codes": [code],
|
||||
"evidence_metric_ids": [ev_b, ev_cov],
|
||||
"action_for_human": "Consider an AMC/CMC. Needs a human decision.",
|
||||
}
|
||||
)
|
||||
|
||||
# --- S3: Active AMC/CMC contract ends within contract lead days AND >= 1 breakdown in period ---
|
||||
if cov_tag in ("amc", "cmc") and period_b >= 1:
|
||||
days_left = cov.get("days_left")
|
||||
if days_left is not None and 0 <= int(days_left) <= contract_lead_days:
|
||||
ev_days = _add_ev(
|
||||
make_metric(
|
||||
f"m_cov_days_left_{slug}",
|
||||
f"Contract Days Remaining ({code})",
|
||||
int(days_left),
|
||||
"days",
|
||||
f"{int(days_left)} days",
|
||||
)
|
||||
)
|
||||
ev_b = _add_ev(
|
||||
make_metric(
|
||||
f"m_bf_count_{slug}",
|
||||
f"Breakdowns in Period ({code})",
|
||||
period_b,
|
||||
"count",
|
||||
)
|
||||
)
|
||||
suggestions.append(
|
||||
{
|
||||
"id": f"S3_{slug}",
|
||||
"rule": "S3",
|
||||
"severity": "yellow",
|
||||
"title": f"Expiring {cov_tag.upper()} with recent breakdowns: {code}",
|
||||
"detail": (
|
||||
f"{code} ({name}) has an active {cov_tag.upper()} expiring in {int(days_left)} day(s) "
|
||||
f"and recorded {period_b} breakdown(s) in the selected period."
|
||||
),
|
||||
"asset_codes": [code],
|
||||
"evidence_metric_ids": [ev_days, ev_b],
|
||||
"action_for_human": "Renewal review before expiry. Needs a human decision.",
|
||||
}
|
||||
)
|
||||
|
||||
# --- S4: maintenance_ratio >= replacement_review_ratio ---
|
||||
maint_ratio = dep_row.get("maintenance_ratio")
|
||||
if maint_ratio is not None and float(maint_ratio) >= review_threshold:
|
||||
ratio_f = float(maint_ratio)
|
||||
sev = "red" if ratio_f >= 1.0 else "yellow"
|
||||
ev_ratio = _add_ev(
|
||||
make_metric(
|
||||
f"m_dep_maint_ratio_{slug}",
|
||||
f"Maintenance Ratio ({code})",
|
||||
round(ratio_f * 100.0, 1),
|
||||
"%",
|
||||
)
|
||||
)
|
||||
ev_maint = _add_ev(
|
||||
make_metric(
|
||||
f"m_dep_maint_cost_{slug}",
|
||||
f"Cumulative Maintenance Cost ({code})",
|
||||
dep_row.get("maintenance_cost"),
|
||||
"INR",
|
||||
)
|
||||
)
|
||||
suggestions.append(
|
||||
{
|
||||
"id": f"S4_{slug}",
|
||||
"rule": "S4",
|
||||
"severity": sev,
|
||||
"title": f"High maintenance-to-purchase ratio on {code} ({ratio_f * 100:.1f}%)",
|
||||
"detail": (
|
||||
f"Cumulative maintenance cost for {code} ({name}) reached "
|
||||
f"{format_inr(dep_row.get('maintenance_cost'))}, which is {ratio_f * 100:.1f}% "
|
||||
f"of purchase value ({format_inr(dep_row.get('purchase_value'))})."
|
||||
),
|
||||
"asset_codes": [code],
|
||||
"evidence_metric_ids": [ev_ratio, ev_maint],
|
||||
"action_for_human": "Replacement review. Needs a human decision.",
|
||||
}
|
||||
)
|
||||
|
||||
# --- S5: scenario_comparison shows another scenario >= 10% cheaper than current set-up ---
|
||||
sc_res = scenario_comparison(
|
||||
a,
|
||||
dataset.get("contracts_by_asset", {}).get(aid, []),
|
||||
dataset.get("complaints_by_asset", {}).get(aid, []),
|
||||
dataset.get("pm_schedules_by_asset", {}).get(aid, []),
|
||||
horizon_years=horizon,
|
||||
as_of=today,
|
||||
settings=cfg,
|
||||
)
|
||||
cur_setup = sc_res.get("current_setup")
|
||||
lowest_key = sc_res.get("lowest_scenario")
|
||||
if cur_setup and lowest_key and lowest_key != cur_setup:
|
||||
cur_scen = sc_res["scenarios"].get(cur_setup, {})
|
||||
low_scen = sc_res["scenarios"].get(lowest_key, {})
|
||||
if cur_scen.get("available") and low_scen.get("available"):
|
||||
cur_cost = float(cur_scen["total_cost"])
|
||||
low_cost = float(low_scen["total_cost"])
|
||||
if cur_cost > 0 and (cur_cost - low_cost) / cur_cost >= 0.10:
|
||||
savings = round(cur_cost - low_cost, 2)
|
||||
pct_save = round((savings / cur_cost) * 100.0, 1)
|
||||
ev_cur = _add_ev(
|
||||
make_metric(
|
||||
f"m_cmp_current_{slug}",
|
||||
f"Current {horizon}-yr Estimate ({code} - {SCENARIO_DISPLAY_NAMES.get(cur_setup, cur_setup)})",
|
||||
cur_cost,
|
||||
"INR",
|
||||
)
|
||||
)
|
||||
ev_low = _add_ev(
|
||||
make_metric(
|
||||
f"m_cmp_lowest_{slug}",
|
||||
f"Lowest {horizon}-yr Estimate ({code} - {SCENARIO_DISPLAY_NAMES.get(lowest_key, lowest_key)})",
|
||||
low_cost,
|
||||
"INR",
|
||||
)
|
||||
)
|
||||
target_label = SCENARIO_DISPLAY_NAMES.get(lowest_key, lowest_key)
|
||||
suggestions.append(
|
||||
{
|
||||
"id": f"S5_{slug}",
|
||||
"rule": "S5",
|
||||
"severity": "info",
|
||||
"title": f"Lower {horizon}-year cost option identified for {code}",
|
||||
"detail": (
|
||||
f"For {code} ({name}), {target_label} ({format_inr(low_cost)}) is "
|
||||
f"{pct_save:.1f}% ({format_inr(savings)}) below current {SCENARIO_DISPLAY_NAMES.get(cur_setup, cur_setup)} "
|
||||
f"({format_inr(cur_cost)}) over {horizon} years."
|
||||
),
|
||||
"asset_codes": [code],
|
||||
"evidence_metric_ids": [ev_cur, ev_low],
|
||||
"action_for_human": f"Evaluate {target_label}. Needs a human decision.",
|
||||
}
|
||||
)
|
||||
|
||||
# --- S6: PM overdue AND >= 1 breakdown in period ---
|
||||
pm_recs = dataset.get("pm_records_by_asset", {}).get(aid, [])
|
||||
overdue_pm_days = 0
|
||||
for rec in pm_recs:
|
||||
if rec.get("status") not in ("completed", "rescheduled"):
|
||||
p_d = _to_date(rec.get("planned_date"))
|
||||
if p_d is not None and p_d < today:
|
||||
overdue_pm_days = max(overdue_pm_days, (today - p_d).days)
|
||||
if overdue_pm_days > 0 and period_b >= 1:
|
||||
ev_pm = _add_ev(
|
||||
make_metric(
|
||||
f"m_pm_overdue_days_{slug}",
|
||||
f"PM Overdue Days ({code})",
|
||||
overdue_pm_days,
|
||||
"days",
|
||||
f"{overdue_pm_days} days overdue",
|
||||
)
|
||||
)
|
||||
ev_b = _add_ev(
|
||||
make_metric(
|
||||
f"m_bf_count_{slug}",
|
||||
f"Breakdowns in Period ({code})",
|
||||
period_b,
|
||||
"count",
|
||||
)
|
||||
)
|
||||
suggestions.append(
|
||||
{
|
||||
"id": f"S6_{slug}",
|
||||
"rule": "S6",
|
||||
"severity": "yellow",
|
||||
"title": f"Overdue PM with active breakdowns on {code}",
|
||||
"detail": (
|
||||
f"{code} ({name}) has preventive maintenance overdue by {overdue_pm_days} day(s) "
|
||||
f"and recorded {period_b} breakdown(s) in the period."
|
||||
),
|
||||
"asset_codes": [code],
|
||||
"evidence_metric_ids": [ev_pm, ev_b],
|
||||
"action_for_human": "Clear overdue PM. Needs a human decision.",
|
||||
}
|
||||
)
|
||||
|
||||
# --- S7: Calibration overdue ---
|
||||
cal_recs = dataset.get("cal_records_by_asset", {}).get(aid, [])
|
||||
cal_plan = dataset.get("cal_plans_by_asset", {}).get(aid)
|
||||
cal_overdue_days = 0
|
||||
open_cal_found = False
|
||||
for cr in cal_recs:
|
||||
if cr.get("status") != "completed":
|
||||
open_cal_found = True
|
||||
d_d = _to_date(cr.get("due_date"))
|
||||
if d_d is not None and d_d < today:
|
||||
cal_overdue_days = max(cal_overdue_days, (today - d_d).days)
|
||||
if not open_cal_found and cal_plan:
|
||||
d_d = _to_date(cal_plan.get("next_due_date"))
|
||||
if d_d is not None and d_d < today:
|
||||
cal_overdue_days = (today - d_d).days
|
||||
|
||||
if cal_overdue_days > 0:
|
||||
sev = "red" if cal_overdue_days > 30 else "yellow"
|
||||
ev_cal = _add_ev(
|
||||
make_metric(
|
||||
f"m_cal_overdue_days_{slug}",
|
||||
f"Calibration Overdue Days ({code})",
|
||||
cal_overdue_days,
|
||||
"days",
|
||||
f"{cal_overdue_days} days overdue",
|
||||
)
|
||||
)
|
||||
suggestions.append(
|
||||
{
|
||||
"id": f"S7_{slug}",
|
||||
"rule": "S7",
|
||||
"severity": sev,
|
||||
"title": f"Calibration overdue on {code} ({cal_overdue_days} days)",
|
||||
"detail": (
|
||||
f"Scheduled calibration for {code} ({name}) is overdue by {cal_overdue_days} day(s)."
|
||||
),
|
||||
"asset_codes": [code],
|
||||
"evidence_metric_ids": [ev_cal],
|
||||
"action_for_human": "Complete calibration. Needs a human decision.",
|
||||
}
|
||||
)
|
||||
|
||||
# --- S8: Fully depreciated AND efficiency_score < 80 ---
|
||||
eff_score = eff_row.get("efficiency_score")
|
||||
if dep_row.get("fully_depreciated") and eff_score is not None and float(eff_score) < 80.0:
|
||||
ev_bv = _add_ev(
|
||||
make_metric(
|
||||
f"m_dep_book_value_{slug}",
|
||||
f"Book Value ({code})",
|
||||
dep_row.get("book_value"),
|
||||
"INR",
|
||||
)
|
||||
)
|
||||
ev_eff = _add_ev(
|
||||
make_metric(
|
||||
f"m_eff_score_{slug}",
|
||||
f"Efficiency Score ({code})",
|
||||
float(eff_score),
|
||||
"score",
|
||||
f"{float(eff_score):.1f} / 100",
|
||||
)
|
||||
)
|
||||
suggestions.append(
|
||||
{
|
||||
"id": f"S8_{slug}",
|
||||
"rule": "S8",
|
||||
"severity": "yellow",
|
||||
"title": f"Fully depreciated asset with low efficiency: {code}",
|
||||
"detail": (
|
||||
f"{code} ({name}) has reached the end of its depreciable life "
|
||||
f"(book value {format_inr(dep_row.get('book_value'))}) with an efficiency score of "
|
||||
f"{float(eff_score):.1f} / 100."
|
||||
),
|
||||
"asset_codes": [code],
|
||||
"evidence_metric_ids": [ev_bv, ev_eff],
|
||||
"action_for_human": "Replacement planning. Needs a human decision.",
|
||||
}
|
||||
)
|
||||
|
||||
suggestions.sort(
|
||||
key=lambda s: (
|
||||
SEVERITY_RANK.get(s["severity"], 9),
|
||||
s["asset_codes"][0] if s["asset_codes"] else "",
|
||||
s["rule"],
|
||||
)
|
||||
)
|
||||
|
||||
return {
|
||||
"suggestions": suggestions,
|
||||
"evidence": list(evidence_by_id.values()),
|
||||
}
|
||||
|
||||
|
||||
def get_suggestions_for_scope(
|
||||
db: Session,
|
||||
user: User,
|
||||
period_start: date,
|
||||
period_end: date,
|
||||
department_id: Optional[int] = None,
|
||||
category_id: Optional[int] = None,
|
||||
) -> dict[str, Any]:
|
||||
dataset = load_ai_dataset(
|
||||
db,
|
||||
user,
|
||||
period_start,
|
||||
period_end,
|
||||
department_id=department_id,
|
||||
category_id=category_id,
|
||||
)
|
||||
return generate_suggestions(dataset)
|
||||
|
||||
@@ -0,0 +1,427 @@
|
||||
from datetime import date, datetime, timezone
|
||||
from sqlalchemy import or_
|
||||
from sqlalchemy.orm import Session, joinedload
|
||||
|
||||
from ..core.time_utils import effective_now_utc, effective_today, format_date
|
||||
from ..models import (
|
||||
Asset,
|
||||
CalibrationRecord,
|
||||
Complaint,
|
||||
Contract,
|
||||
DemoEquipment,
|
||||
InsurancePolicy,
|
||||
Notification,
|
||||
NotificationRead,
|
||||
PMRecord,
|
||||
PMSchedule,
|
||||
User,
|
||||
Warranty,
|
||||
)
|
||||
from .calculations import alert_state, compute_sla_status
|
||||
from .permissions import Role
|
||||
from .settings_service import get_setting_value
|
||||
|
||||
|
||||
def _ensure_utc(dt: datetime) -> datetime:
|
||||
if dt.tzinfo is None:
|
||||
return dt.replace(tzinfo=timezone.utc)
|
||||
return dt.astimezone(timezone.utc)
|
||||
|
||||
|
||||
def notification_link_url(entity_type: str, entity_id: int) -> str:
|
||||
mapping = {
|
||||
"contract": "/contracts",
|
||||
"warranty": "/contracts?tab=warranties",
|
||||
"calibration_record": "/calibration",
|
||||
"pm_record": "/pm",
|
||||
"insurance": "/insurance",
|
||||
"demo_equipment": "/demo-equipment",
|
||||
"complaint": f"/complaints/{entity_id}",
|
||||
}
|
||||
return mapping.get(entity_type, "/")
|
||||
|
||||
|
||||
def _alert_settings(db: Session) -> dict[str, int]:
|
||||
return {
|
||||
"amc": int(
|
||||
get_setting_value(
|
||||
db,
|
||||
"amc_cmc_lead_days",
|
||||
get_setting_value(db, "contract_expiry_alert_days", 30),
|
||||
)
|
||||
),
|
||||
"calibration": int(
|
||||
get_setting_value(
|
||||
db,
|
||||
"calibration_due_window_days",
|
||||
get_setting_value(db, "calibration_lead_days", 15),
|
||||
)
|
||||
),
|
||||
"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)),
|
||||
"insurance": int(
|
||||
get_setting_value(
|
||||
db,
|
||||
"insurance_lead_days",
|
||||
get_setting_value(db, "insurance_expiry_alert_days", 30),
|
||||
)
|
||||
),
|
||||
"warranty": int(
|
||||
get_setting_value(
|
||||
db,
|
||||
"warranty_lead_days",
|
||||
get_setting_value(db, "warranty_expiry_alert_days", 30),
|
||||
)
|
||||
),
|
||||
"contract_red": int(
|
||||
get_setting_value(
|
||||
db,
|
||||
"contract_critical_alert_days",
|
||||
get_setting_value(db, "red_threshold_days", 7),
|
||||
)
|
||||
),
|
||||
"red": int(get_setting_value(db, "red_threshold_days", 7)),
|
||||
"critical_hours": int(
|
||||
get_setting_value(
|
||||
db,
|
||||
"critical_complaint_alert_hours",
|
||||
get_setting_value(db, "escalation_open_complaint_hours", 24),
|
||||
)
|
||||
),
|
||||
"critical_sla_hours": int(get_setting_value(db, "critical_complaint_sla_hours", 4)),
|
||||
"non_critical_sla_hours": int(get_setting_value(db, "non_critical_complaint_sla_hours", 24)),
|
||||
}
|
||||
|
||||
|
||||
def _add_if_new(
|
||||
db: Session,
|
||||
existing_keys: set[str],
|
||||
*,
|
||||
dedupe_key: str,
|
||||
alert_type: str,
|
||||
severity: str,
|
||||
title: str,
|
||||
message: str,
|
||||
entity_type: str,
|
||||
entity_id: int,
|
||||
due_date: date | None,
|
||||
target_role: str,
|
||||
created_at: datetime,
|
||||
) -> int:
|
||||
if dedupe_key in existing_keys:
|
||||
return 0
|
||||
existing_keys.add(dedupe_key)
|
||||
db.add(
|
||||
Notification(
|
||||
type=alert_type,
|
||||
severity=severity,
|
||||
title=title,
|
||||
message=message,
|
||||
entity_type=entity_type,
|
||||
entity_id=entity_id,
|
||||
due_date=due_date,
|
||||
target_role=target_role,
|
||||
target_user_id=None,
|
||||
dedupe_key=dedupe_key,
|
||||
created_at=created_at,
|
||||
)
|
||||
)
|
||||
return 1
|
||||
|
||||
|
||||
def run_alert_check(db: Session) -> dict[str, object]:
|
||||
today = effective_today(db)
|
||||
eff_now = effective_now_utc(db)
|
||||
cfg = _alert_settings(db)
|
||||
|
||||
existing_keys = {row[0] for row in db.query(Notification.dedupe_key).all()}
|
||||
created = 0
|
||||
|
||||
# 1. AMC / CMC / OTHER contracts expiring
|
||||
contracts = (
|
||||
db.query(Contract)
|
||||
.options(joinedload(Contract.asset))
|
||||
.filter(Contract.is_superseded.is_(False))
|
||||
.all()
|
||||
)
|
||||
for c in contracts:
|
||||
state = alert_state(c.end_date, today, cfg["amc"], cfg["contract_red"])
|
||||
if state in ("yellow", "red"):
|
||||
created += _add_if_new(
|
||||
db,
|
||||
existing_keys,
|
||||
dedupe_key=f"amc:{c.id}:{state}",
|
||||
alert_type="amc_expiry",
|
||||
severity=state,
|
||||
title=f"{c.contract_type} Contract {'Critical' if state == 'red' else 'Expiring'}: {c.asset.asset_code}",
|
||||
message=f"{c.contract_type} contract for {c.asset.name} ({c.asset.asset_code}) ends on {format_date(c.end_date)}.",
|
||||
entity_type="contract",
|
||||
entity_id=c.id,
|
||||
due_date=c.end_date,
|
||||
target_role="coordinator,management,biomedical,system_admin",
|
||||
created_at=eff_now,
|
||||
)
|
||||
|
||||
# 2. Calibration due / overdue
|
||||
cal_records = (
|
||||
db.query(CalibrationRecord)
|
||||
.options(joinedload(CalibrationRecord.asset))
|
||||
.filter(or_(CalibrationRecord.status.is_(None), CalibrationRecord.status != "completed"))
|
||||
.all()
|
||||
)
|
||||
for r in cal_records:
|
||||
state = alert_state(r.due_date, today, cfg["calibration"], cfg["red"])
|
||||
if state in ("yellow", "red"):
|
||||
status_word = "Overdue" if r.due_date < today else "Due Soon"
|
||||
created += _add_if_new(
|
||||
db,
|
||||
existing_keys,
|
||||
dedupe_key=f"cal:{r.id}:{state}",
|
||||
alert_type="calibration_due",
|
||||
severity=state,
|
||||
title=f"Calibration {status_word}: {r.asset.asset_code}",
|
||||
message=f"Calibration for {r.asset.name} ({r.asset.asset_code}) is due on {format_date(r.due_date)}.",
|
||||
entity_type="calibration_record",
|
||||
entity_id=r.id,
|
||||
due_date=r.due_date,
|
||||
target_role="biomedical,coordinator,management,system_admin",
|
||||
created_at=eff_now,
|
||||
)
|
||||
|
||||
# 3. PM due / overdue
|
||||
pm_records = (
|
||||
db.query(PMRecord)
|
||||
.options(joinedload(PMRecord.asset), joinedload(PMRecord.schedule))
|
||||
.filter(or_(PMRecord.status.is_(None), ~PMRecord.status.in_(["completed", "rescheduled"])))
|
||||
.all()
|
||||
)
|
||||
for r in pm_records:
|
||||
mode = r.schedule.service_mode if r.schedule else "in_house"
|
||||
lead = cfg["pm_in_house"] if mode == "in_house" else cfg["pm_outsourced"]
|
||||
state = alert_state(r.planned_date, today, lead, cfg["red"])
|
||||
if state in ("yellow", "red"):
|
||||
status_word = "Overdue" if r.planned_date < today else "Due Soon"
|
||||
created += _add_if_new(
|
||||
db,
|
||||
existing_keys,
|
||||
dedupe_key=f"pm:{r.id}:{state}",
|
||||
alert_type="pm_due",
|
||||
severity=state,
|
||||
title=f"PM {status_word}: {r.asset.asset_code}",
|
||||
message=f"Preventive maintenance ({mode.replace('_', '-')}) for {r.asset.name} ({r.asset.asset_code}) is planned for {format_date(r.planned_date)}.",
|
||||
entity_type="pm_record",
|
||||
entity_id=r.id,
|
||||
due_date=r.planned_date,
|
||||
target_role="biomedical,coordinator,management,system_admin",
|
||||
created_at=eff_now,
|
||||
)
|
||||
|
||||
# 4. Insurance expiry
|
||||
policies = db.query(InsurancePolicy).options(joinedload(InsurancePolicy.asset)).all()
|
||||
for p in policies:
|
||||
state = alert_state(p.end_date, today, cfg["insurance"], cfg["red"])
|
||||
if state in ("yellow", "red"):
|
||||
created += _add_if_new(
|
||||
db,
|
||||
existing_keys,
|
||||
dedupe_key=f"ins:{p.id}:{state}",
|
||||
alert_type="insurance_expiry",
|
||||
severity=state,
|
||||
title=f"Insurance {'Critical' if state == 'red' else 'Expiring'}: {p.asset.asset_code}",
|
||||
message=f"Policy {p.policy_no} for {p.asset.name} ({p.asset.asset_code}) ends on {format_date(p.end_date)}.",
|
||||
entity_type="insurance",
|
||||
entity_id=p.id,
|
||||
due_date=p.end_date,
|
||||
target_role="coordinator,management,system_admin",
|
||||
created_at=eff_now,
|
||||
)
|
||||
|
||||
# 5. Warranty expiry
|
||||
warranties = db.query(Warranty).options(joinedload(Warranty.asset)).all()
|
||||
for w in warranties:
|
||||
state = alert_state(w.end_date, today, cfg["warranty"], cfg["red"])
|
||||
if state in ("yellow", "red"):
|
||||
created += _add_if_new(
|
||||
db,
|
||||
existing_keys,
|
||||
dedupe_key=f"war:{w.id}:{state}",
|
||||
alert_type="warranty_expiry",
|
||||
severity=state,
|
||||
title=f"Warranty {'Critical' if state == 'red' else 'Expiring'}: {w.asset.asset_code}",
|
||||
message=f"Warranty for {w.asset.name} ({w.asset.asset_code}) ends on {format_date(w.end_date)}.",
|
||||
entity_type="warranty",
|
||||
entity_id=w.id,
|
||||
due_date=w.end_date,
|
||||
target_role="coordinator,biomedical,management,system_admin",
|
||||
created_at=eff_now,
|
||||
)
|
||||
|
||||
# 6. Demo equipment overdue return
|
||||
demos = (
|
||||
db.query(DemoEquipment)
|
||||
.filter(DemoEquipment.actual_return_date.is_(None), DemoEquipment.expected_return_date < today)
|
||||
.all()
|
||||
)
|
||||
for d in demos:
|
||||
created += _add_if_new(
|
||||
db,
|
||||
existing_keys,
|
||||
dedupe_key=f"demo:{d.id}:overdue",
|
||||
alert_type="demo_overdue",
|
||||
severity="red",
|
||||
title=f"Demo Return Overdue: {d.name}",
|
||||
message=f"Demo equipment '{d.name}' expected back on {format_date(d.expected_return_date)} has not been returned.",
|
||||
entity_type="demo_equipment",
|
||||
entity_id=d.id,
|
||||
due_date=d.expected_return_date,
|
||||
target_role="biomedical,coordinator,management,system_admin",
|
||||
created_at=eff_now,
|
||||
)
|
||||
|
||||
# 7. Critical complaints open >= escalation_open_complaint_hours (and not yet restored)
|
||||
crit_complaints = (
|
||||
db.query(Complaint)
|
||||
.options(joinedload(Complaint.asset))
|
||||
.filter(
|
||||
Complaint.call_status != "closed",
|
||||
Complaint.priority == "critical",
|
||||
Complaint.restored_at.is_(None),
|
||||
)
|
||||
.all()
|
||||
)
|
||||
threshold_secs = cfg["critical_hours"] * 3600
|
||||
for c in crit_complaints:
|
||||
elapsed = (_ensure_utc(eff_now) - _ensure_utc(c.registered_at)).total_seconds()
|
||||
if elapsed >= threshold_secs:
|
||||
created += _add_if_new(
|
||||
db,
|
||||
existing_keys,
|
||||
dedupe_key=f"cmp:{c.id}:critical_overdue",
|
||||
alert_type="critical_complaint",
|
||||
severity="red",
|
||||
title=f"Critical Complaint Open > {cfg['critical_hours']}h: {c.complaint_no}",
|
||||
message=f"Critical complaint {c.complaint_no} for {c.asset.name} ({c.asset.asset_code}) remains {c.call_status}.",
|
||||
entity_type="complaint",
|
||||
entity_id=c.id,
|
||||
due_date=today,
|
||||
target_role="biomedical,management,system_admin,department_user",
|
||||
created_at=eff_now,
|
||||
)
|
||||
|
||||
# 8. Open unrestored complaints breaching configured SLA hours
|
||||
open_unrestored = (
|
||||
db.query(Complaint)
|
||||
.options(joinedload(Complaint.asset))
|
||||
.filter(Complaint.call_status != "closed", Complaint.restored_at.is_(None))
|
||||
.all()
|
||||
)
|
||||
for c in open_unrestored:
|
||||
sla_breached, sla_hours = compute_sla_status(
|
||||
c.priority,
|
||||
c.registered_at,
|
||||
c.attended_at,
|
||||
c.restored_at,
|
||||
critical_sla_hours=cfg["critical_sla_hours"],
|
||||
non_critical_sla_hours=cfg["non_critical_sla_hours"],
|
||||
now_utc=eff_now,
|
||||
)
|
||||
if sla_breached:
|
||||
created += _add_if_new(
|
||||
db,
|
||||
existing_keys,
|
||||
dedupe_key=f"cmp:{c.id}:sla_breach",
|
||||
alert_type="sla_breach",
|
||||
severity="red",
|
||||
title=f"SLA Breach: Open > {sla_hours}h: {c.complaint_no}",
|
||||
message=f"Complaint {c.complaint_no} for {c.asset.name} ({c.asset.asset_code}) exceeded {sla_hours}h SLA without restoration.",
|
||||
entity_type="complaint",
|
||||
entity_id=c.id,
|
||||
due_date=today,
|
||||
target_role="biomedical,management,system_admin,department_user",
|
||||
created_at=eff_now,
|
||||
)
|
||||
|
||||
db.flush()
|
||||
return {"created": created, "evaluated_today": today.isoformat()}
|
||||
|
||||
|
||||
def _resolve_entity_departments(db: Session, notifications: list[Notification]) -> dict[tuple[str, int], int]:
|
||||
by_type: dict[str, list[int]] = {}
|
||||
for n in notifications:
|
||||
by_type.setdefault(n.entity_type, []).append(n.entity_id)
|
||||
|
||||
dept_map: dict[tuple[str, int], int] = {}
|
||||
|
||||
asset_model_map = {
|
||||
"contract": Contract,
|
||||
"warranty": Warranty,
|
||||
"insurance": InsurancePolicy,
|
||||
"calibration_record": CalibrationRecord,
|
||||
"pm_record": PMRecord,
|
||||
"complaint": Complaint,
|
||||
}
|
||||
for etype, model in asset_model_map.items():
|
||||
ids = list(set(by_type.get(etype, [])))
|
||||
if ids:
|
||||
rows = (
|
||||
db.query(model.id, Asset.department_id)
|
||||
.join(Asset, model.asset_id == Asset.id)
|
||||
.filter(model.id.in_(ids))
|
||||
.all()
|
||||
)
|
||||
for eid, dept_id in rows:
|
||||
dept_map[(etype, eid)] = dept_id
|
||||
|
||||
demo_ids = list(set(by_type.get("demo_equipment", [])))
|
||||
if demo_ids:
|
||||
rows = (
|
||||
db.query(DemoEquipment.id, DemoEquipment.department_id)
|
||||
.filter(DemoEquipment.id.in_(demo_ids))
|
||||
.all()
|
||||
)
|
||||
for eid, dept_id in rows:
|
||||
dept_map[("demo_equipment", eid)] = dept_id
|
||||
|
||||
return dept_map
|
||||
|
||||
|
||||
def get_visible_notifications_for_user(
|
||||
db: Session,
|
||||
user: User,
|
||||
) -> tuple[list[Notification], dict[int, datetime]]:
|
||||
"""Return (visible_notifications_ordered, read_at_by_notification_id) for the given user."""
|
||||
all_rows = (
|
||||
db.query(Notification)
|
||||
.order_by(Notification.created_at.desc(), Notification.id.desc())
|
||||
.all()
|
||||
)
|
||||
role_filtered: list[Notification] = []
|
||||
for n in all_rows:
|
||||
roles = {r.strip() for r in (n.target_role or "").split(",") if r.strip()}
|
||||
if user.role in roles or n.target_user_id == user.id:
|
||||
role_filtered.append(n)
|
||||
|
||||
if user.role == Role.department_user.value:
|
||||
dept_map = _resolve_entity_departments(db, role_filtered)
|
||||
visible = [
|
||||
n
|
||||
for n in role_filtered
|
||||
if dept_map.get((n.entity_type, n.entity_id)) == user.department_id
|
||||
]
|
||||
else:
|
||||
visible = role_filtered
|
||||
|
||||
visible_ids = [n.id for n in visible]
|
||||
read_map: dict[int, datetime] = {}
|
||||
if visible_ids:
|
||||
reads = (
|
||||
db.query(NotificationRead)
|
||||
.filter(
|
||||
NotificationRead.user_id == user.id,
|
||||
NotificationRead.notification_id.in_(visible_ids),
|
||||
)
|
||||
.all()
|
||||
)
|
||||
read_map = {r.notification_id: r.read_at for r in reads}
|
||||
|
||||
return visible, read_map
|
||||
@@ -0,0 +1,585 @@
|
||||
import csv
|
||||
from datetime import date, datetime, timedelta
|
||||
from io import BytesIO, StringIO
|
||||
from pathlib import Path
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
import openpyxl
|
||||
from openpyxl.styles import Alignment, Border, Font, PatternFill, Side
|
||||
from openpyxl.utils import get_column_letter
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..core.exceptions import CodedHTTPException
|
||||
from ..models import Asset, Category, Department, Location, Vendor
|
||||
from .audit import log_audit
|
||||
from .settings_service import get_setting_value
|
||||
|
||||
IMPORT_COLUMNS = [
|
||||
"asset_code",
|
||||
"serial_no",
|
||||
"name",
|
||||
"category",
|
||||
"department",
|
||||
"location",
|
||||
"supplier",
|
||||
"purchase_value",
|
||||
"purchase_date",
|
||||
"installation_date",
|
||||
"status",
|
||||
"criticality",
|
||||
"requires_calibration",
|
||||
"insurance_applicable",
|
||||
"remarks",
|
||||
"acquisition_mode",
|
||||
"monthly_rent",
|
||||
"useful_life_years",
|
||||
"salvage_pct",
|
||||
"depreciation_method",
|
||||
]
|
||||
|
||||
VALID_STATUSES = ("in_service", "under_repair", "out_of_service", "condemned")
|
||||
VALID_CRITICALITIES = ("critical", "non_critical")
|
||||
VALID_ACQUISITION_MODES = ("purchased", "rented")
|
||||
VALID_DEPRECIATION_METHODS = ("straight_line", "written_down")
|
||||
|
||||
_HEADER_FILL = PatternFill(start_color="1E3A8A", end_color="1E3A8A", fill_type="solid")
|
||||
_HEADER_FONT = Font(name="Calibri", size=11, color="FFFFFF", bold=True)
|
||||
_HEADER_BORDER = Border(
|
||||
left=Side(style="thin", color="334155"),
|
||||
right=Side(style="thin", color="334155"),
|
||||
top=Side(style="thin", color="334155"),
|
||||
bottom=Side(style="medium", color="0F172A"),
|
||||
)
|
||||
|
||||
|
||||
def _auto_fit_columns(ws, max_width: int = 42) -> None:
|
||||
for col_idx in range(1, ws.max_column + 1):
|
||||
max_len = 0
|
||||
for row_idx in range(1, ws.max_row + 1):
|
||||
val = ws.cell(row=row_idx, column=col_idx).value
|
||||
if val is not None:
|
||||
max_len = max(max_len, len(str(val)))
|
||||
ws.column_dimensions[get_column_letter(col_idx)].width = min(max(max_len + 4, 14), max_width)
|
||||
|
||||
|
||||
def build_import_template_xlsx(db: Session) -> BytesIO:
|
||||
wb = openpyxl.Workbook()
|
||||
ws = wb.active
|
||||
ws.title = "Assets"
|
||||
|
||||
for col_idx, col_name in enumerate(IMPORT_COLUMNS, start=1):
|
||||
cell = ws.cell(row=1, column=col_idx, value=col_name)
|
||||
cell.fill = _HEADER_FILL
|
||||
cell.font = _HEADER_FONT
|
||||
cell.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
|
||||
cell.border = _HEADER_BORDER
|
||||
ws.row_dimensions[1].height = 26
|
||||
ws.views.sheetView[0].showGridLines = True
|
||||
ws.auto_filter.ref = f"A1:{get_column_letter(len(IMPORT_COLUMNS))}1"
|
||||
ws.freeze_panes = "A2"
|
||||
|
||||
departments = (
|
||||
db.query(Department)
|
||||
.filter(Department.is_active.is_(True))
|
||||
.order_by(Department.code.asc())
|
||||
.all()
|
||||
)
|
||||
locations = (
|
||||
db.query(Location)
|
||||
.join(Department, Location.department_id == Department.id)
|
||||
.filter(Location.is_active.is_(True), Department.is_active.is_(True))
|
||||
.order_by(Department.code.asc(), Location.name.asc())
|
||||
.all()
|
||||
)
|
||||
categories = (
|
||||
db.query(Category)
|
||||
.filter(Category.is_active.is_(True))
|
||||
.order_by(Category.name.asc())
|
||||
.all()
|
||||
)
|
||||
vendors = (
|
||||
db.query(Vendor)
|
||||
.filter(Vendor.is_active.is_(True))
|
||||
.order_by(Vendor.name.asc())
|
||||
.all()
|
||||
)
|
||||
|
||||
sample_dept = departments[0] if departments else None
|
||||
sample_loc = (
|
||||
next((loc for loc in locations if sample_dept and loc.department_id == sample_dept.id), None)
|
||||
or (locations[0] if locations else None)
|
||||
)
|
||||
sample_cat = categories[0] if categories else None
|
||||
sample_sup = vendors[0] if vendors else None
|
||||
|
||||
sample_prefix = str(get_setting_value(db, "asset_code_prefix", "PHRC")).strip() or "PHRC"
|
||||
sample_dept_code = sample_dept.code if sample_dept else "ICU"
|
||||
sample_row = [
|
||||
f"{sample_prefix}-{sample_dept_code}-0901",
|
||||
"SN-DEMO-901",
|
||||
"Infusion Pump",
|
||||
sample_cat.name if sample_cat else "Infusion Pump",
|
||||
sample_dept.code if sample_dept else "ICU",
|
||||
sample_loc.name if sample_loc else "ICU Bay 1",
|
||||
sample_sup.name if sample_sup else "",
|
||||
125000,
|
||||
"2025-01-15",
|
||||
"2025-01-20",
|
||||
"in_service",
|
||||
"critical",
|
||||
"true",
|
||||
"false",
|
||||
"Sample row - replace or remove before import",
|
||||
"purchased",
|
||||
3500,
|
||||
10,
|
||||
5,
|
||||
"straight_line",
|
||||
]
|
||||
_auto_fit_columns(ws)
|
||||
|
||||
# Sheet 2: Example
|
||||
ws_ex = wb.create_sheet(title="Example")
|
||||
ws_ex.views.sheetView[0].showGridLines = True
|
||||
ws_ex.cell(row=1, column=1, value="Example only - this sheet is ignored on import")
|
||||
for col_idx, val in enumerate(sample_row, start=1):
|
||||
ws_ex.cell(row=2, column=col_idx, value=val)
|
||||
_auto_fit_columns(ws_ex)
|
||||
|
||||
# Sheet 3: Master Reference
|
||||
ref = wb.create_sheet(title="Master Reference")
|
||||
ref.row_dimensions[1].height = 26
|
||||
ref.views.sheetView[0].showGridLines = True
|
||||
headers_map = [
|
||||
(1, "Department Code"),
|
||||
(2, "Department Name"),
|
||||
(4, "Department Code"),
|
||||
(5, "Location Name"),
|
||||
(7, "Category Name"),
|
||||
(9, "Supplier Name"),
|
||||
(11, "Valid Statuses"),
|
||||
(13, "Valid Criticality"),
|
||||
(15, "Acquisition Modes"),
|
||||
(17, "Depreciation Methods"),
|
||||
]
|
||||
for col_idx, label in headers_map:
|
||||
c = ref.cell(row=1, column=col_idx, value=label)
|
||||
c.fill = _HEADER_FILL
|
||||
c.font = _HEADER_FONT
|
||||
c.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
|
||||
c.border = _HEADER_BORDER
|
||||
ref.freeze_panes = "A2"
|
||||
|
||||
dept_by_id = {d.id: d for d in departments}
|
||||
for idx, d in enumerate(departments, start=2):
|
||||
ref.cell(row=idx, column=1, value=d.code)
|
||||
ref.cell(row=idx, column=2, value=d.name)
|
||||
|
||||
for idx, loc in enumerate(locations, start=2):
|
||||
d = dept_by_id.get(loc.department_id)
|
||||
ref.cell(row=idx, column=4, value=d.code if d else "")
|
||||
ref.cell(row=idx, column=5, value=loc.name)
|
||||
|
||||
for idx, cat in enumerate(categories, start=2):
|
||||
ref.cell(row=idx, column=7, value=cat.name)
|
||||
|
||||
for idx, v in enumerate(vendors, start=2):
|
||||
ref.cell(row=idx, column=9, value=v.name)
|
||||
|
||||
for idx, st in enumerate(VALID_STATUSES, start=2):
|
||||
ref.cell(row=idx, column=11, value=st)
|
||||
|
||||
for idx, crit in enumerate(VALID_CRITICALITIES, start=2):
|
||||
ref.cell(row=idx, column=13, value=crit)
|
||||
|
||||
for idx, mode in enumerate(VALID_ACQUISITION_MODES, start=2):
|
||||
ref.cell(row=idx, column=15, value=mode)
|
||||
|
||||
for idx, dm in enumerate(VALID_DEPRECIATION_METHODS, start=2):
|
||||
ref.cell(row=idx, column=17, value=dm)
|
||||
|
||||
_auto_fit_columns(ref)
|
||||
|
||||
buf = BytesIO()
|
||||
wb.save(buf)
|
||||
buf.seek(0)
|
||||
return buf
|
||||
|
||||
|
||||
def _clean_str(val: Any) -> str:
|
||||
if val is None:
|
||||
return ""
|
||||
if isinstance(val, float) and val.is_integer():
|
||||
return str(int(val))
|
||||
return str(val).strip()
|
||||
|
||||
|
||||
def _parse_optional_date(val: Any, field_name: str) -> tuple[date | None, str | None]:
|
||||
if val is None or (isinstance(val, str) and not val.strip()):
|
||||
return None, None
|
||||
if isinstance(val, datetime):
|
||||
return val.date(), None
|
||||
if isinstance(val, date):
|
||||
return val, None
|
||||
if isinstance(val, (int, float)) and 20000 <= val <= 80000:
|
||||
try:
|
||||
return (datetime(1899, 12, 30) + timedelta(days=int(val))).date(), None
|
||||
except Exception:
|
||||
pass
|
||||
text = str(val).strip()
|
||||
for fmt in (
|
||||
"%Y-%m-%d",
|
||||
"%d-%b-%Y",
|
||||
"%d/%m/%Y",
|
||||
"%m/%d/%Y",
|
||||
"%Y/%m/%d",
|
||||
"%d-%m-%Y",
|
||||
"%d.%m.%Y",
|
||||
"%d %b %Y",
|
||||
):
|
||||
try:
|
||||
return datetime.strptime(text, fmt).date(), None
|
||||
except ValueError:
|
||||
continue
|
||||
return None, f"Invalid {field_name} '{text}' (expected YYYY-MM-DD or DD-MMM-YYYY)"
|
||||
|
||||
|
||||
def _parse_bool(val: Any, field_name: str) -> tuple[bool, str | None]:
|
||||
if val is None or (isinstance(val, str) and not val.strip()):
|
||||
return False, None
|
||||
if isinstance(val, bool):
|
||||
return val, None
|
||||
if isinstance(val, (int, float)) and val in (0, 1):
|
||||
return bool(val), None
|
||||
text = str(val).strip().lower()
|
||||
if text in ("true", "yes", "1", "y"):
|
||||
return True, None
|
||||
if text in ("false", "no", "0", "n"):
|
||||
return False, None
|
||||
return False, f"Invalid {field_name} '{val}' (use true/false or yes/no)"
|
||||
|
||||
|
||||
def _parse_optional_float(val: Any, field_name: str) -> tuple[float | None, str | None]:
|
||||
if val is None or (isinstance(val, str) and not val.strip()):
|
||||
return None, None
|
||||
if isinstance(val, (int, float)):
|
||||
if val < 0:
|
||||
return None, f"{field_name} cannot be negative"
|
||||
return float(val), None
|
||||
cleaned = re.sub(r"[₹$,\s]|(?i:rs\.?|inr)", "", str(val).strip())
|
||||
if not cleaned:
|
||||
return None, None
|
||||
try:
|
||||
parsed = float(cleaned)
|
||||
except (TypeError, ValueError):
|
||||
return None, f"Invalid {field_name} '{val}' (must be a number)"
|
||||
if parsed < 0:
|
||||
return None, f"{field_name} cannot be negative"
|
||||
return parsed, None
|
||||
|
||||
|
||||
def _extract_rows(filename: str, content: bytes) -> list[tuple[int, dict[str, Any]]]:
|
||||
ext = Path(filename or "").suffix.lower()
|
||||
if ext not in (".xlsx", ".csv"):
|
||||
raise CodedHTTPException(
|
||||
status_code=400,
|
||||
detail="Unsupported file type. Please upload an .xlsx or .csv file.",
|
||||
code="INVALID_FILE_TYPE",
|
||||
)
|
||||
|
||||
rows_out: list[tuple[int, dict[str, Any]]] = []
|
||||
if ext == ".xlsx":
|
||||
try:
|
||||
wb = openpyxl.load_workbook(BytesIO(content), data_only=True)
|
||||
except Exception as exc:
|
||||
raise CodedHTTPException(
|
||||
status_code=400,
|
||||
detail="Invalid Excel file. Please download and use the import template.",
|
||||
code="INVALID_FILE_TYPE",
|
||||
) from exc
|
||||
ws = wb.worksheets[0]
|
||||
header_cells = next(ws.iter_rows(min_row=1, max_row=1, values_only=True), None)
|
||||
if not header_cells:
|
||||
return []
|
||||
headers = [_clean_str(h).lower().replace(" ", "_") for h in header_cells]
|
||||
for row_idx, row_vals in enumerate(ws.iter_rows(min_row=2, values_only=True), start=2):
|
||||
if all(v is None or _clean_str(v) == "" for v in row_vals):
|
||||
continue
|
||||
row_dict = {
|
||||
headers[i]: (row_vals[i] if i < len(row_vals) else None)
|
||||
for i in range(len(headers))
|
||||
if headers[i]
|
||||
}
|
||||
rows_out.append((row_idx, row_dict))
|
||||
else:
|
||||
try:
|
||||
decoded = content.decode("utf-8-sig")
|
||||
except UnicodeDecodeError:
|
||||
decoded = content.decode("latin-1")
|
||||
reader = csv.reader(StringIO(decoded))
|
||||
header_row = next(reader, None)
|
||||
if not header_row:
|
||||
return []
|
||||
headers = [_clean_str(h).lower().replace(" ", "_") for h in header_row]
|
||||
for row_idx, row_vals in enumerate(reader, start=2):
|
||||
if all(_clean_str(v) == "" for v in row_vals):
|
||||
continue
|
||||
row_dict = {
|
||||
headers[i]: (row_vals[i] if i < len(row_vals) else None)
|
||||
for i in range(len(headers))
|
||||
if headers[i]
|
||||
}
|
||||
rows_out.append((row_idx, row_dict))
|
||||
return rows_out
|
||||
|
||||
|
||||
def process_asset_import(
|
||||
db: Session,
|
||||
filename: str,
|
||||
content: bytes,
|
||||
user_id: int,
|
||||
dry_run: bool = False,
|
||||
skip_invalid: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
raw_rows = _extract_rows(filename, content)
|
||||
|
||||
departments = db.query(Department).filter(Department.is_active.is_(True)).all()
|
||||
dept_lookup: dict[str, Department] = {}
|
||||
for d in departments:
|
||||
dept_lookup[d.code.strip().lower()] = d
|
||||
dept_lookup[d.name.strip().lower()] = d
|
||||
|
||||
locations = db.query(Location).filter(Location.is_active.is_(True)).all()
|
||||
loc_lookup: dict[tuple[int, str], Location] = {
|
||||
(loc.department_id, loc.name.strip().lower()): loc for loc in locations
|
||||
}
|
||||
|
||||
categories = db.query(Category).filter(Category.is_active.is_(True)).all()
|
||||
cat_lookup: dict[str, Category] = {c.name.strip().lower(): c for c in categories}
|
||||
|
||||
vendors = db.query(Vendor).filter(Vendor.is_active.is_(True)).all()
|
||||
vendor_lookup: dict[str, Vendor] = {v.name.strip().lower(): v for v in vendors}
|
||||
|
||||
existing_codes = {
|
||||
code.strip().lower() for (code,) in db.query(Asset.asset_code).all() if code
|
||||
}
|
||||
seen_codes: set[str] = set()
|
||||
|
||||
errors: list[dict[str, Any]] = []
|
||||
preview_rows: list[dict[str, Any]] = []
|
||||
valid_assets: list[Asset] = []
|
||||
|
||||
for row_idx, row_dict in raw_rows:
|
||||
row_errors: list[str] = []
|
||||
|
||||
asset_code = _clean_str(row_dict.get("asset_code"))
|
||||
serial_no = _clean_str(row_dict.get("serial_no"))
|
||||
name = _clean_str(row_dict.get("name"))
|
||||
cat_raw = _clean_str(row_dict.get("category"))
|
||||
dept_raw = _clean_str(row_dict.get("department"))
|
||||
loc_raw = _clean_str(row_dict.get("location"))
|
||||
sup_raw = _clean_str(row_dict.get("supplier"))
|
||||
remarks = _clean_str(row_dict.get("remarks")) or None
|
||||
|
||||
for req_label, req_val in (
|
||||
("asset_code", asset_code),
|
||||
("serial_no", serial_no),
|
||||
("name", name),
|
||||
("category", cat_raw),
|
||||
("department", dept_raw),
|
||||
("location", loc_raw),
|
||||
):
|
||||
if not req_val:
|
||||
row_errors.append(f"Missing required field '{req_label}'")
|
||||
|
||||
if asset_code:
|
||||
code_norm = asset_code.lower()
|
||||
if code_norm in existing_codes:
|
||||
row_errors.append(f"Duplicate asset_code '{asset_code}' already exists in database")
|
||||
elif code_norm in seen_codes:
|
||||
row_errors.append(f"Duplicate asset_code '{asset_code}' within import file")
|
||||
seen_codes.add(code_norm)
|
||||
|
||||
dept_obj = dept_lookup.get(dept_raw.lower()) if dept_raw else None
|
||||
if dept_raw and dept_obj is None:
|
||||
row_errors.append(f"Unknown active department '{dept_raw}'")
|
||||
|
||||
loc_obj = None
|
||||
if loc_raw and dept_obj is not None:
|
||||
loc_obj = loc_lookup.get((dept_obj.id, loc_raw.lower()))
|
||||
if loc_obj is None:
|
||||
row_errors.append(
|
||||
f"Unknown active location '{loc_raw}' in department '{dept_obj.name}'"
|
||||
)
|
||||
|
||||
cat_obj = cat_lookup.get(cat_raw.lower()) if cat_raw else None
|
||||
if cat_raw and cat_obj is None:
|
||||
row_errors.append(f"Unknown active category '{cat_raw}'")
|
||||
|
||||
sup_obj = None
|
||||
if sup_raw:
|
||||
sup_obj = vendor_lookup.get(sup_raw.lower())
|
||||
if sup_obj is None:
|
||||
row_errors.append(f"Unknown active supplier '{sup_raw}'")
|
||||
|
||||
purchase_value, val_err = _parse_optional_float(row_dict.get("purchase_value"), "purchase_value")
|
||||
if val_err:
|
||||
row_errors.append(val_err)
|
||||
|
||||
acq_raw = _clean_str(row_dict.get("acquisition_mode"))
|
||||
acq_val = acq_raw.lower().replace(" ", "_") if acq_raw else "purchased"
|
||||
if acq_val not in VALID_ACQUISITION_MODES:
|
||||
row_errors.append(
|
||||
f"Invalid acquisition_mode '{acq_raw}' (valid: {', '.join(VALID_ACQUISITION_MODES)})"
|
||||
)
|
||||
|
||||
monthly_rent, rent_err = _parse_optional_float(row_dict.get("monthly_rent"), "monthly_rent")
|
||||
if rent_err:
|
||||
row_errors.append(rent_err)
|
||||
|
||||
useful_life_raw = _clean_str(row_dict.get("useful_life_years"))
|
||||
useful_life_years: int | None = None
|
||||
if useful_life_raw:
|
||||
try:
|
||||
ul_f = float(useful_life_raw)
|
||||
ul_i = int(ul_f)
|
||||
if ul_i < 1 or ul_i > 100 or ul_i != ul_f:
|
||||
row_errors.append(f"Invalid useful_life_years '{useful_life_raw}' (must be an integer 1-100)")
|
||||
else:
|
||||
useful_life_years = ul_i
|
||||
except (TypeError, ValueError):
|
||||
row_errors.append(f"Invalid useful_life_years '{useful_life_raw}' (must be an integer 1-100)")
|
||||
|
||||
salvage_pct, salv_err = _parse_optional_float(row_dict.get("salvage_pct"), "salvage_pct")
|
||||
if salv_err:
|
||||
row_errors.append(salv_err)
|
||||
elif salvage_pct is not None and salvage_pct > 50:
|
||||
row_errors.append("salvage_pct must be between 0 and 50")
|
||||
|
||||
dm_raw = _clean_str(row_dict.get("depreciation_method"))
|
||||
dm_val: str | None = dm_raw.lower().replace(" ", "_") if dm_raw else None
|
||||
if dm_val is not None and dm_val not in VALID_DEPRECIATION_METHODS:
|
||||
row_errors.append(
|
||||
f"Invalid depreciation_method '{dm_raw}' (valid: {', '.join(VALID_DEPRECIATION_METHODS)})"
|
||||
)
|
||||
|
||||
purchase_date, pdate_err = _parse_optional_date(row_dict.get("purchase_date"), "purchase_date")
|
||||
if pdate_err:
|
||||
row_errors.append(pdate_err)
|
||||
|
||||
installation_date, idate_err = _parse_optional_date(
|
||||
row_dict.get("installation_date"), "installation_date"
|
||||
)
|
||||
if idate_err:
|
||||
row_errors.append(idate_err)
|
||||
|
||||
status_raw = _clean_str(row_dict.get("status"))
|
||||
status_val = status_raw.lower().replace(" ", "_") if status_raw else "in_service"
|
||||
if status_val not in VALID_STATUSES:
|
||||
row_errors.append(f"Invalid status '{status_raw}' (valid: {', '.join(VALID_STATUSES)})")
|
||||
|
||||
crit_raw = _clean_str(row_dict.get("criticality"))
|
||||
crit_val = crit_raw.lower().replace(" ", "_") if crit_raw else "non_critical"
|
||||
if crit_val not in VALID_CRITICALITIES:
|
||||
row_errors.append(
|
||||
f"Invalid criticality '{crit_raw}' (valid: {', '.join(VALID_CRITICALITIES)})"
|
||||
)
|
||||
|
||||
req_cal, cal_err = _parse_bool(row_dict.get("requires_calibration"), "requires_calibration")
|
||||
if cal_err:
|
||||
row_errors.append(cal_err)
|
||||
|
||||
ins_app, ins_err = _parse_bool(row_dict.get("insurance_applicable"), "insurance_applicable")
|
||||
if ins_err:
|
||||
row_errors.append(ins_err)
|
||||
|
||||
is_valid = len(row_errors) == 0
|
||||
err_text = "; ".join(row_errors) if row_errors else None
|
||||
if not is_valid:
|
||||
errors.append(
|
||||
{
|
||||
"row": row_idx,
|
||||
"asset_code": asset_code or None,
|
||||
"error": err_text,
|
||||
}
|
||||
)
|
||||
else:
|
||||
valid_assets.append(
|
||||
Asset(
|
||||
asset_code=asset_code,
|
||||
serial_no=serial_no,
|
||||
name=name,
|
||||
category_id=cat_obj.id,
|
||||
department_id=dept_obj.id,
|
||||
location_id=loc_obj.id,
|
||||
supplier_id=sup_obj.id if sup_obj else None,
|
||||
purchase_value=purchase_value,
|
||||
acquisition_mode=acq_val,
|
||||
monthly_rent=monthly_rent,
|
||||
useful_life_years=useful_life_years,
|
||||
salvage_pct=salvage_pct,
|
||||
depreciation_method=dm_val,
|
||||
purchase_date=purchase_date,
|
||||
installation_date=installation_date,
|
||||
status=status_val,
|
||||
criticality=crit_val,
|
||||
requires_calibration=req_cal,
|
||||
insurance_applicable=ins_app,
|
||||
remarks=remarks,
|
||||
created_by_id=user_id,
|
||||
updated_by_id=user_id,
|
||||
)
|
||||
)
|
||||
|
||||
preview_rows.append(
|
||||
{
|
||||
"row": row_idx,
|
||||
"asset_code": asset_code or None,
|
||||
"serial_no": serial_no or None,
|
||||
"name": name or None,
|
||||
"category_name": cat_obj.name if cat_obj else (cat_raw or None),
|
||||
"department_name": dept_obj.name if dept_obj else (dept_raw or None),
|
||||
"location_name": loc_obj.name if loc_obj else (loc_raw or None),
|
||||
"status": status_val,
|
||||
"valid": is_valid,
|
||||
"error": err_text,
|
||||
}
|
||||
)
|
||||
|
||||
created_count = 0
|
||||
if not dry_run:
|
||||
if errors and not skip_invalid:
|
||||
raise CodedHTTPException(
|
||||
status_code=400,
|
||||
detail=f"{len(errors)} row(s) failed validation.",
|
||||
code="IMPORT_VALIDATION_ERRORS",
|
||||
)
|
||||
if valid_assets:
|
||||
db.add_all(valid_assets)
|
||||
db.flush()
|
||||
for a in valid_assets:
|
||||
log_audit(
|
||||
db,
|
||||
entity_type="asset",
|
||||
entity_id=a.id,
|
||||
action="bulk_import",
|
||||
changes={
|
||||
"asset_code": a.asset_code,
|
||||
"name": a.name,
|
||||
"department_id": a.department_id,
|
||||
},
|
||||
user_id=user_id,
|
||||
)
|
||||
db.commit()
|
||||
created_count = len(valid_assets)
|
||||
|
||||
return {
|
||||
"dry_run": dry_run,
|
||||
"total_rows": len(raw_rows),
|
||||
"valid_count": len(valid_assets),
|
||||
"error_count": len(errors),
|
||||
"created_count": created_count,
|
||||
"errors": errors,
|
||||
"preview_rows": preview_rows,
|
||||
}
|
||||
@@ -0,0 +1,332 @@
|
||||
from pathlib import Path
|
||||
from uuid import uuid4
|
||||
from fastapi import UploadFile
|
||||
from sqlalchemy import func
|
||||
from sqlalchemy.orm import Session, joinedload
|
||||
|
||||
from ..core.config import settings
|
||||
from ..core.exceptions import CodedHTTPException
|
||||
from ..core.time_utils import utc_now
|
||||
from ..models import (
|
||||
Asset,
|
||||
Attachment,
|
||||
CalibrationRecord,
|
||||
Complaint,
|
||||
Contract,
|
||||
DemoEquipment,
|
||||
InsurancePolicy,
|
||||
PMRecord,
|
||||
PMSchedule,
|
||||
User,
|
||||
Warranty,
|
||||
)
|
||||
from ..services.audit import log_audit
|
||||
from ..services.permissions import Role
|
||||
|
||||
ALLOWED_ENTITY_TYPES: set[str] = {
|
||||
"complaint",
|
||||
"contract",
|
||||
"calibration_record",
|
||||
"insurance",
|
||||
"demo_equipment",
|
||||
"asset",
|
||||
"warranty",
|
||||
"pm_record",
|
||||
}
|
||||
|
||||
EXT_TO_MIME: dict[str, str] = {
|
||||
".jpg": "image/jpeg",
|
||||
".jpeg": "image/jpeg",
|
||||
".png": "image/png",
|
||||
".pdf": "application/pdf",
|
||||
}
|
||||
|
||||
ACCEPTED_CONTENT_TYPES: dict[str, set[str]] = {
|
||||
"image/jpeg": {"image/jpeg", "image/jpg", "image/pjpeg", "application/octet-stream", ""},
|
||||
"image/png": {"image/png", "application/octet-stream", ""},
|
||||
"application/pdf": {"application/pdf", "application/octet-stream", ""},
|
||||
}
|
||||
|
||||
COORDINATOR_UPLOAD_ENTITIES: set[str] = {
|
||||
"contract",
|
||||
"calibration_record",
|
||||
"insurance",
|
||||
"warranty",
|
||||
"demo_equipment",
|
||||
"pm_record",
|
||||
}
|
||||
|
||||
|
||||
def resolve_entity_department_id(db: Session, entity_type: str, entity_id: int) -> int:
|
||||
if entity_type not in ALLOWED_ENTITY_TYPES:
|
||||
raise CodedHTTPException(
|
||||
status_code=400,
|
||||
detail=f"Unsupported entity_type '{entity_type}'.",
|
||||
code="INVALID_ENTITY_TYPE",
|
||||
)
|
||||
|
||||
if entity_type == "asset":
|
||||
obj = db.query(Asset).filter(Asset.id == entity_id).first()
|
||||
if obj is None:
|
||||
raise CodedHTTPException(status_code=404, detail="Asset not found.", code="NOT_FOUND")
|
||||
return obj.department_id
|
||||
|
||||
if entity_type == "complaint":
|
||||
obj = (
|
||||
db.query(Complaint)
|
||||
.options(joinedload(Complaint.asset))
|
||||
.filter(Complaint.id == entity_id)
|
||||
.first()
|
||||
)
|
||||
if obj is None:
|
||||
raise CodedHTTPException(status_code=404, detail="Complaint not found.", code="NOT_FOUND")
|
||||
return obj.asset.department_id
|
||||
|
||||
if entity_type == "demo_equipment":
|
||||
obj = db.query(DemoEquipment).filter(DemoEquipment.id == entity_id).first()
|
||||
if obj is None:
|
||||
raise CodedHTTPException(status_code=404, detail="Demo equipment not found.", code="NOT_FOUND")
|
||||
return obj.department_id
|
||||
|
||||
if entity_type == "contract":
|
||||
obj = (
|
||||
db.query(Contract)
|
||||
.options(joinedload(Contract.asset))
|
||||
.filter(Contract.id == entity_id)
|
||||
.first()
|
||||
)
|
||||
if obj is None:
|
||||
raise CodedHTTPException(status_code=404, detail="Contract not found.", code="NOT_FOUND")
|
||||
return obj.asset.department_id
|
||||
|
||||
if entity_type == "warranty":
|
||||
obj = (
|
||||
db.query(Warranty)
|
||||
.options(joinedload(Warranty.asset))
|
||||
.filter(Warranty.id == entity_id)
|
||||
.first()
|
||||
)
|
||||
if obj is None:
|
||||
raise CodedHTTPException(status_code=404, detail="Warranty not found.", code="NOT_FOUND")
|
||||
return obj.asset.department_id
|
||||
|
||||
if entity_type == "insurance":
|
||||
obj = (
|
||||
db.query(InsurancePolicy)
|
||||
.options(joinedload(InsurancePolicy.asset))
|
||||
.filter(InsurancePolicy.id == entity_id)
|
||||
.first()
|
||||
)
|
||||
if obj is None:
|
||||
raise CodedHTTPException(status_code=404, detail="Insurance policy not found.", code="NOT_FOUND")
|
||||
return obj.asset.department_id
|
||||
|
||||
if entity_type == "calibration_record":
|
||||
obj = (
|
||||
db.query(CalibrationRecord)
|
||||
.options(joinedload(CalibrationRecord.asset))
|
||||
.filter(CalibrationRecord.id == entity_id)
|
||||
.first()
|
||||
)
|
||||
if obj is None:
|
||||
raise CodedHTTPException(status_code=404, detail="Calibration record not found.", code="NOT_FOUND")
|
||||
return obj.asset.department_id
|
||||
|
||||
if entity_type == "pm_record":
|
||||
obj = (
|
||||
db.query(PMRecord)
|
||||
.options(joinedload(PMRecord.schedule).joinedload(PMSchedule.asset))
|
||||
.filter(PMRecord.id == entity_id)
|
||||
.first()
|
||||
)
|
||||
if obj is None:
|
||||
raise CodedHTTPException(status_code=404, detail="PM record not found.", code="NOT_FOUND")
|
||||
return obj.schedule.asset.department_id
|
||||
|
||||
raise CodedHTTPException(status_code=400, detail="Unsupported entity_type.", code="INVALID_ENTITY_TYPE")
|
||||
|
||||
|
||||
def assert_entity_visible(db: Session, user: User, entity_type: str, entity_id: int) -> int:
|
||||
dept_id = resolve_entity_department_id(db, entity_type, entity_id)
|
||||
if user.role == Role.department_user.value and dept_id != user.department_id:
|
||||
raise CodedHTTPException(
|
||||
status_code=403,
|
||||
detail="Access denied for another department's record.",
|
||||
code="FORBIDDEN",
|
||||
)
|
||||
return dept_id
|
||||
|
||||
|
||||
def assert_can_upload(user: User, entity_type: str) -> None:
|
||||
if user.role in (Role.system_admin.value, Role.biomedical.value):
|
||||
return
|
||||
if user.role == Role.department_user.value:
|
||||
if entity_type != "complaint":
|
||||
raise CodedHTTPException(
|
||||
status_code=403,
|
||||
detail="Department users may only upload attachments to complaints.",
|
||||
code="FORBIDDEN",
|
||||
)
|
||||
return
|
||||
if user.role == Role.coordinator.value:
|
||||
if entity_type not in COORDINATOR_UPLOAD_ENTITIES:
|
||||
raise CodedHTTPException(
|
||||
status_code=403,
|
||||
detail=f"Coordinators cannot upload attachments to '{entity_type}'.",
|
||||
code="FORBIDDEN",
|
||||
)
|
||||
return
|
||||
raise CodedHTTPException(
|
||||
status_code=403,
|
||||
detail="You do not have permission to upload attachments.",
|
||||
code="FORBIDDEN",
|
||||
)
|
||||
|
||||
|
||||
def assert_can_delete(user: User, att: Attachment) -> None:
|
||||
if user.role in (Role.system_admin.value, Role.biomedical.value):
|
||||
return
|
||||
if user.role != Role.management.value and att.uploaded_by_id == user.id:
|
||||
return
|
||||
raise CodedHTTPException(
|
||||
status_code=403,
|
||||
detail="You do not have permission to delete this attachment.",
|
||||
code="FORBIDDEN",
|
||||
)
|
||||
|
||||
|
||||
def validate_and_read_upload(file: UploadFile) -> tuple[str, str, bytes]:
|
||||
original_name = Path(file.filename or "").name
|
||||
ext = Path(original_name).suffix.lower()
|
||||
if ext not in EXT_TO_MIME:
|
||||
raise CodedHTTPException(
|
||||
status_code=400,
|
||||
detail="Only JPG, JPEG, PNG, and PDF files are allowed.",
|
||||
code="INVALID_FILE_TYPE",
|
||||
)
|
||||
|
||||
expected_mime = EXT_TO_MIME[ext]
|
||||
claimed_type = (file.content_type or "").lower().strip()
|
||||
if claimed_type not in ACCEPTED_CONTENT_TYPES[expected_mime]:
|
||||
raise CodedHTTPException(
|
||||
status_code=400,
|
||||
detail=f"Invalid content type '{claimed_type}' for {ext} file.",
|
||||
code="INVALID_FILE_TYPE",
|
||||
)
|
||||
|
||||
max_bytes = settings.MAX_UPLOAD_SIZE_MB * 1024 * 1024
|
||||
content = file.file.read(max_bytes + 1)
|
||||
if len(content) > max_bytes:
|
||||
raise CodedHTTPException(
|
||||
status_code=413,
|
||||
detail=f"File size exceeds the {settings.MAX_UPLOAD_SIZE_MB} MB limit.",
|
||||
code="FILE_TOO_LARGE",
|
||||
)
|
||||
if len(content) == 0:
|
||||
raise CodedHTTPException(
|
||||
status_code=400,
|
||||
detail="Uploaded file is empty.",
|
||||
code="INVALID_FILE_TYPE",
|
||||
)
|
||||
|
||||
# Magic bytes verification
|
||||
if expected_mime == "image/jpeg" and not content.startswith(b"\xff\xd8\xff"):
|
||||
raise CodedHTTPException(
|
||||
status_code=400,
|
||||
detail="File contents do not match a valid JPEG image.",
|
||||
code="INVALID_FILE_TYPE",
|
||||
)
|
||||
if expected_mime == "image/png" and not content.startswith(b"\x89PNG\r\n\x1a\n"):
|
||||
raise CodedHTTPException(
|
||||
status_code=400,
|
||||
detail="File contents do not match a valid PNG image.",
|
||||
code="INVALID_FILE_TYPE",
|
||||
)
|
||||
if expected_mime == "application/pdf" and not content.startswith(b"%PDF-"):
|
||||
raise CodedHTTPException(
|
||||
status_code=400,
|
||||
detail="File contents do not match a valid PDF document.",
|
||||
code="INVALID_FILE_TYPE",
|
||||
)
|
||||
|
||||
return original_name, expected_mime, content
|
||||
|
||||
|
||||
def save_attachment(
|
||||
db: Session,
|
||||
user: User,
|
||||
entity_type: str,
|
||||
entity_id: int,
|
||||
file: UploadFile,
|
||||
) -> Attachment:
|
||||
assert_entity_visible(db, user, entity_type, entity_id)
|
||||
assert_can_upload(user, entity_type)
|
||||
|
||||
original_name, mime_type, content = validate_and_read_upload(file)
|
||||
ext = Path(original_name).suffix.lower()
|
||||
stored_name = f"{uuid4().hex}{ext}"
|
||||
|
||||
upload_dir = Path(settings.UPLOAD_DIR)
|
||||
upload_dir.mkdir(parents=True, exist_ok=True)
|
||||
dest_path = upload_dir / stored_name
|
||||
dest_path.write_bytes(content)
|
||||
|
||||
att = Attachment(
|
||||
entity_type=entity_type,
|
||||
entity_id=entity_id,
|
||||
original_name=original_name,
|
||||
stored_name=stored_name,
|
||||
mime_type=mime_type,
|
||||
size_bytes=len(content),
|
||||
uploaded_by_id=user.id,
|
||||
uploaded_at=utc_now(),
|
||||
)
|
||||
db.add(att)
|
||||
db.flush()
|
||||
log_audit(
|
||||
db,
|
||||
entity_type="attachment",
|
||||
entity_id=att.id,
|
||||
action="upload",
|
||||
changes={"parent_type": entity_type, "parent_id": entity_id, "original_name": original_name},
|
||||
user_id=user.id,
|
||||
)
|
||||
db.commit()
|
||||
db.refresh(att)
|
||||
return att
|
||||
|
||||
|
||||
def delete_attachment(db: Session, user: User, attachment_id: int) -> None:
|
||||
att = db.query(Attachment).filter(Attachment.id == attachment_id).first()
|
||||
if att is None:
|
||||
raise CodedHTTPException(status_code=404, detail="Attachment not found.", code="NOT_FOUND")
|
||||
|
||||
assert_entity_visible(db, user, att.entity_type, att.entity_id)
|
||||
assert_can_delete(user, att)
|
||||
|
||||
file_path = Path(settings.UPLOAD_DIR) / att.stored_name
|
||||
if file_path.is_file():
|
||||
file_path.unlink()
|
||||
|
||||
log_audit(
|
||||
db,
|
||||
entity_type="attachment",
|
||||
entity_id=att.id,
|
||||
action="delete",
|
||||
changes={"parent_type": att.entity_type, "parent_id": att.entity_id, "original_name": att.original_name},
|
||||
user_id=user.id,
|
||||
)
|
||||
db.delete(att)
|
||||
db.commit()
|
||||
|
||||
|
||||
def get_attachment_counts(db: Session, entity_type: str, entity_ids: list[int]) -> dict[int, int]:
|
||||
if not entity_ids:
|
||||
return {}
|
||||
rows = (
|
||||
db.query(Attachment.entity_id, func.count(Attachment.id))
|
||||
.filter(Attachment.entity_type == entity_type, Attachment.entity_id.in_(entity_ids))
|
||||
.group_by(Attachment.entity_id)
|
||||
.all()
|
||||
)
|
||||
return {eid: cnt for eid, cnt in rows}
|
||||
@@ -0,0 +1,25 @@
|
||||
import json
|
||||
from typing import Any
|
||||
from sqlalchemy.orm import Session
|
||||
from ..core.time_utils import utc_now
|
||||
from ..models.system import AuditLog
|
||||
|
||||
|
||||
def log_audit(
|
||||
db: Session,
|
||||
entity_type: str,
|
||||
entity_id: int,
|
||||
action: str,
|
||||
changes: dict[str, Any],
|
||||
user_id: int | None,
|
||||
) -> AuditLog:
|
||||
entry = AuditLog(
|
||||
entity_type=entity_type,
|
||||
entity_id=entity_id,
|
||||
action=action,
|
||||
changes_json=json.dumps(changes, default=str),
|
||||
by_user_id=user_id,
|
||||
at=utc_now(),
|
||||
)
|
||||
db.add(entry)
|
||||
return entry
|
||||
@@ -0,0 +1,986 @@
|
||||
"""
|
||||
Poona Hospital Asset Management System
|
||||
Bulk Import Template Builders for Contracts, Calibration Plans, and Insurance Policies.
|
||||
"""
|
||||
|
||||
import csv
|
||||
from datetime import date, datetime, timedelta
|
||||
from io import BytesIO, StringIO
|
||||
from pathlib import Path
|
||||
import re
|
||||
from typing import Any
|
||||
|
||||
import openpyxl
|
||||
from openpyxl.styles import Alignment, Border, Font, PatternFill, Side
|
||||
from openpyxl.utils import get_column_letter
|
||||
from sqlalchemy.orm import Session
|
||||
|
||||
from ..core.exceptions import CodedHTTPException
|
||||
from ..core.time_utils import add_months, effective_today
|
||||
from ..models import (
|
||||
Asset,
|
||||
CalibrationPlan,
|
||||
CalibrationRecord,
|
||||
Contract,
|
||||
Department,
|
||||
InsurancePolicy,
|
||||
Vendor,
|
||||
)
|
||||
from .audit import log_audit
|
||||
from .settings_service import get_setting_value
|
||||
|
||||
_HEADER_FILL = PatternFill(start_color="1E3A8A", end_color="1E3A8A", fill_type="solid")
|
||||
_HEADER_FONT = Font(name="Calibri", size=11, color="FFFFFF", bold=True)
|
||||
_REF_HEADER_FILL = PatternFill(start_color="334155", end_color="334155", fill_type="solid")
|
||||
_HEADER_BORDER = Border(
|
||||
left=Side(style="thin", color="334155"),
|
||||
right=Side(style="thin", color="334155"),
|
||||
top=Side(style="thin", color="334155"),
|
||||
bottom=Side(style="medium", color="0F172A"),
|
||||
)
|
||||
|
||||
|
||||
def _auto_fit_columns(ws, max_width: int = 42) -> None:
|
||||
for col_idx in range(1, ws.max_column + 1):
|
||||
max_len = 0
|
||||
for row_idx in range(1, ws.max_row + 1):
|
||||
val = ws.cell(row=row_idx, column=col_idx).value
|
||||
if val is not None:
|
||||
max_len = max(max_len, len(str(val)))
|
||||
ws.column_dimensions[get_column_letter(col_idx)].width = min(max(max_len + 4, 14), max_width)
|
||||
|
||||
|
||||
def build_contracts_template_xlsx(db: Session) -> BytesIO:
|
||||
wb = openpyxl.Workbook()
|
||||
ws = wb.active
|
||||
ws.title = "Contracts"
|
||||
|
||||
cols = [
|
||||
"asset_code",
|
||||
"provider_name",
|
||||
"contract_type",
|
||||
"start_date",
|
||||
"end_date",
|
||||
"contract_value",
|
||||
"coverage_details",
|
||||
"remarks",
|
||||
]
|
||||
for col_idx, col_name in enumerate(cols, start=1):
|
||||
c = ws.cell(row=1, column=col_idx, value=col_name)
|
||||
c.fill = _HEADER_FILL
|
||||
c.font = _HEADER_FONT
|
||||
c.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
|
||||
c.border = _HEADER_BORDER
|
||||
ws.row_dimensions[1].height = 26
|
||||
ws.views.sheetView[0].showGridLines = True
|
||||
ws.auto_filter.ref = f"A1:{get_column_letter(len(cols))}1"
|
||||
ws.freeze_panes = "A2"
|
||||
|
||||
assets = db.query(Asset).join(Department).filter(Asset.status != "condemned").order_by(Asset.asset_code).all()
|
||||
vendors = db.query(Vendor).filter(Vendor.is_active.is_(True)).order_by(Vendor.name).all()
|
||||
|
||||
sample_asset = assets[0] if assets else None
|
||||
sample_vendor = vendors[0] if vendors else None
|
||||
sample_row = [
|
||||
sample_asset.asset_code if sample_asset else "PHRC-ICU-0001",
|
||||
sample_vendor.name if sample_vendor else "Wipro GE Healthcare Pvt Ltd",
|
||||
"CMC",
|
||||
"2026-01-01",
|
||||
"2026-12-31",
|
||||
75000,
|
||||
"Comprehensive maintenance with all spare parts included",
|
||||
"Annual contract renewal",
|
||||
]
|
||||
_auto_fit_columns(ws)
|
||||
|
||||
# Sheet 2: Example
|
||||
ws_ex = wb.create_sheet(title="Example")
|
||||
ws_ex.views.sheetView[0].showGridLines = True
|
||||
ws_ex.cell(row=1, column=1, value="Example only - this sheet is ignored on import")
|
||||
for col_idx, val in enumerate(sample_row, start=1):
|
||||
ws_ex.cell(row=2, column=col_idx, value=val)
|
||||
_auto_fit_columns(ws_ex)
|
||||
|
||||
# Sheet 3: Master Reference
|
||||
ws_ref = wb.create_sheet(title="Master Reference")
|
||||
ws_ref.row_dimensions[1].height = 26
|
||||
ws_ref.views.sheetView[0].showGridLines = True
|
||||
ws_ref.cell(row=1, column=1, value="Asset Code").fill = _REF_HEADER_FILL
|
||||
ws_ref.cell(row=1, column=1).font = _HEADER_FONT
|
||||
ws_ref.cell(row=1, column=2, value="Asset Name").fill = _REF_HEADER_FILL
|
||||
ws_ref.cell(row=1, column=2).font = _HEADER_FONT
|
||||
ws_ref.cell(row=1, column=3, value="Department").fill = _REF_HEADER_FILL
|
||||
ws_ref.cell(row=1, column=3).font = _HEADER_FONT
|
||||
|
||||
ws_ref.cell(row=1, column=5, value="Vendor / Provider").fill = _REF_HEADER_FILL
|
||||
ws_ref.cell(row=1, column=5).font = _HEADER_FONT
|
||||
|
||||
ws_ref.cell(row=1, column=7, value="Valid Contract Types").fill = _REF_HEADER_FILL
|
||||
ws_ref.cell(row=1, column=7).font = _HEADER_FONT
|
||||
|
||||
for r_idx, a in enumerate(assets[:100], start=2):
|
||||
ws_ref.cell(row=r_idx, column=1, value=a.asset_code)
|
||||
ws_ref.cell(row=r_idx, column=2, value=a.name)
|
||||
ws_ref.cell(row=r_idx, column=3, value=a.department.name if a.department else "")
|
||||
|
||||
for r_idx, v in enumerate(vendors, start=2):
|
||||
ws_ref.cell(row=r_idx, column=5, value=v.name)
|
||||
|
||||
for r_idx, ct in enumerate(["AMC", "CMC", "OTHER"], start=2):
|
||||
ws_ref.cell(row=r_idx, column=7, value=ct)
|
||||
|
||||
_auto_fit_columns(ws_ref)
|
||||
buf = BytesIO()
|
||||
wb.save(buf)
|
||||
buf.seek(0)
|
||||
return buf
|
||||
|
||||
|
||||
def build_calibration_template_xlsx(db: Session) -> BytesIO:
|
||||
wb = openpyxl.Workbook()
|
||||
ws = wb.active
|
||||
ws.title = "Calibration Plans"
|
||||
|
||||
cols = [
|
||||
"asset_code",
|
||||
"frequency_months",
|
||||
"agency_name",
|
||||
"scope",
|
||||
"standards",
|
||||
"remarks",
|
||||
]
|
||||
for col_idx, col_name in enumerate(cols, start=1):
|
||||
c = ws.cell(row=1, column=col_idx, value=col_name)
|
||||
c.fill = _HEADER_FILL
|
||||
c.font = _HEADER_FONT
|
||||
c.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
|
||||
c.border = _HEADER_BORDER
|
||||
ws.row_dimensions[1].height = 26
|
||||
ws.views.sheetView[0].showGridLines = True
|
||||
ws.auto_filter.ref = f"A1:{get_column_letter(len(cols))}1"
|
||||
ws.freeze_panes = "A2"
|
||||
|
||||
assets = (
|
||||
db.query(Asset)
|
||||
.join(Department)
|
||||
.filter(Asset.status != "condemned", Asset.requires_calibration.is_(True))
|
||||
.order_by(Asset.asset_code)
|
||||
.all()
|
||||
)
|
||||
if not assets:
|
||||
assets = db.query(Asset).join(Department).filter(Asset.status != "condemned").order_by(Asset.asset_code).all()
|
||||
|
||||
vendors = db.query(Vendor).filter(Vendor.is_active.is_(True)).order_by(Vendor.name).all()
|
||||
sample_asset = assets[0] if assets else None
|
||||
sample_vendor = vendors[0] if vendors else None
|
||||
|
||||
sample_row = [
|
||||
sample_asset.asset_code if sample_asset else "PHRC-ICU-0001",
|
||||
12,
|
||||
sample_vendor.name if sample_vendor else "National Calibration Laboratory",
|
||||
"Pressure and Flow accuracy verification",
|
||||
"ISO/IEC 17025 accredited",
|
||||
"Annual calibration plan",
|
||||
]
|
||||
_auto_fit_columns(ws)
|
||||
|
||||
# Sheet 2: Example
|
||||
ws_ex = wb.create_sheet(title="Example")
|
||||
ws_ex.views.sheetView[0].showGridLines = True
|
||||
ws_ex.cell(row=1, column=1, value="Example only - this sheet is ignored on import")
|
||||
for col_idx, val in enumerate(sample_row, start=1):
|
||||
ws_ex.cell(row=2, column=col_idx, value=val)
|
||||
_auto_fit_columns(ws_ex)
|
||||
|
||||
# Sheet 3: Master Reference
|
||||
ws_ref = wb.create_sheet(title="Master Reference")
|
||||
ws_ref.row_dimensions[1].height = 26
|
||||
ws_ref.views.sheetView[0].showGridLines = True
|
||||
ws_ref.cell(row=1, column=1, value="Asset Code").fill = _REF_HEADER_FILL
|
||||
ws_ref.cell(row=1, column=1).font = _HEADER_FONT
|
||||
ws_ref.cell(row=1, column=2, value="Asset Name").fill = _REF_HEADER_FILL
|
||||
ws_ref.cell(row=1, column=2).font = _HEADER_FONT
|
||||
ws_ref.cell(row=1, column=3, value="Department").fill = _REF_HEADER_FILL
|
||||
ws_ref.cell(row=1, column=3).font = _HEADER_FONT
|
||||
|
||||
ws_ref.cell(row=1, column=5, value="Calibration Agencies").fill = _REF_HEADER_FILL
|
||||
ws_ref.cell(row=1, column=5).font = _HEADER_FONT
|
||||
|
||||
ws_ref.cell(row=1, column=7, value="Recommended Frequencies").fill = _REF_HEADER_FILL
|
||||
ws_ref.cell(row=1, column=7).font = _HEADER_FONT
|
||||
|
||||
for r_idx, a in enumerate(assets[:100], start=2):
|
||||
ws_ref.cell(row=r_idx, column=1, value=a.asset_code)
|
||||
ws_ref.cell(row=r_idx, column=2, value=a.name)
|
||||
ws_ref.cell(row=r_idx, column=3, value=a.department.name if a.department else "")
|
||||
|
||||
for r_idx, v in enumerate(vendors, start=2):
|
||||
ws_ref.cell(row=r_idx, column=5, value=v.name)
|
||||
|
||||
for r_idx, freq in enumerate(["3 (Quarterly)", "6 (Semi-Annual)", "12 (Annual)", "24 (Biennial)"], start=2):
|
||||
ws_ref.cell(row=r_idx, column=7, value=freq)
|
||||
|
||||
_auto_fit_columns(ws_ref)
|
||||
buf = BytesIO()
|
||||
wb.save(buf)
|
||||
buf.seek(0)
|
||||
return buf
|
||||
|
||||
|
||||
def build_insurance_template_xlsx(db: Session) -> BytesIO:
|
||||
wb = openpyxl.Workbook()
|
||||
ws = wb.active
|
||||
ws.title = "Insurance Policies"
|
||||
|
||||
cols = [
|
||||
"asset_code",
|
||||
"insurer_name",
|
||||
"policy_number",
|
||||
"start_date",
|
||||
"end_date",
|
||||
"insured_value",
|
||||
"premium",
|
||||
"remarks",
|
||||
]
|
||||
for col_idx, col_name in enumerate(cols, start=1):
|
||||
c = ws.cell(row=1, column=col_idx, value=col_name)
|
||||
c.fill = _HEADER_FILL
|
||||
c.font = _HEADER_FONT
|
||||
c.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
|
||||
c.border = _HEADER_BORDER
|
||||
ws.row_dimensions[1].height = 26
|
||||
ws.views.sheetView[0].showGridLines = True
|
||||
ws.auto_filter.ref = f"A1:{get_column_letter(len(cols))}1"
|
||||
ws.freeze_panes = "A2"
|
||||
|
||||
assets = db.query(Asset).join(Department).filter(Asset.status != "condemned").order_by(Asset.asset_code).all()
|
||||
sample_asset = assets[0] if assets else None
|
||||
|
||||
sample_row = [
|
||||
sample_asset.asset_code if sample_asset else "PHRC-ICU-0001",
|
||||
"New India Assurance Co. Ltd",
|
||||
"NIA-MH-2026-MED-4412",
|
||||
"2026-04-01",
|
||||
"2027-03-31",
|
||||
1500000,
|
||||
18500,
|
||||
"Annual hospital equipment comprehensive policy",
|
||||
]
|
||||
_auto_fit_columns(ws)
|
||||
|
||||
# Sheet 2: Example
|
||||
ws_ex = wb.create_sheet(title="Example")
|
||||
ws_ex.views.sheetView[0].showGridLines = True
|
||||
ws_ex.cell(row=1, column=1, value="Example only - this sheet is ignored on import")
|
||||
for col_idx, val in enumerate(sample_row, start=1):
|
||||
ws_ex.cell(row=2, column=col_idx, value=val)
|
||||
_auto_fit_columns(ws_ex)
|
||||
|
||||
# Sheet 3: Master Reference
|
||||
ws_ref = wb.create_sheet(title="Master Reference")
|
||||
ws_ref.row_dimensions[1].height = 26
|
||||
ws_ref.views.sheetView[0].showGridLines = True
|
||||
ws_ref.cell(row=1, column=1, value="Asset Code").fill = _REF_HEADER_FILL
|
||||
ws_ref.cell(row=1, column=1).font = _HEADER_FONT
|
||||
ws_ref.cell(row=1, column=2, value="Asset Name").fill = _REF_HEADER_FILL
|
||||
ws_ref.cell(row=1, column=2).font = _HEADER_FONT
|
||||
ws_ref.cell(row=1, column=3, value="Department").fill = _REF_HEADER_FILL
|
||||
ws_ref.cell(row=1, column=3).font = _HEADER_FONT
|
||||
|
||||
for r_idx, a in enumerate(assets[:100], start=2):
|
||||
ws_ref.cell(row=r_idx, column=1, value=a.asset_code)
|
||||
ws_ref.cell(row=r_idx, column=2, value=a.name)
|
||||
ws_ref.cell(row=r_idx, column=3, value=a.department.name if a.department else "")
|
||||
|
||||
_auto_fit_columns(ws_ref)
|
||||
buf = BytesIO()
|
||||
wb.save(buf)
|
||||
buf.seek(0)
|
||||
return buf
|
||||
|
||||
|
||||
def _clean_str(val: Any) -> str:
|
||||
if val is None:
|
||||
return ""
|
||||
if isinstance(val, float) and val.is_integer():
|
||||
return str(int(val))
|
||||
return str(val).strip()
|
||||
|
||||
|
||||
def _parse_date(val: Any, field_name: str) -> tuple[date | None, str | None]:
|
||||
if val is None or (isinstance(val, str) and not val.strip()):
|
||||
return None, f"Missing required field '{field_name}'"
|
||||
if isinstance(val, datetime):
|
||||
return val.date(), None
|
||||
if isinstance(val, date):
|
||||
return val, None
|
||||
if isinstance(val, (int, float)) and 20000 <= val <= 80000:
|
||||
try:
|
||||
return (datetime(1899, 12, 30) + timedelta(days=int(val))).date(), None
|
||||
except Exception:
|
||||
pass
|
||||
text = str(val).strip()
|
||||
for fmt in (
|
||||
"%Y-%m-%d",
|
||||
"%d-%b-%Y",
|
||||
"%d/%m/%Y",
|
||||
"%m/%d/%Y",
|
||||
"%Y/%m/%d",
|
||||
"%d-%m-%Y",
|
||||
"%d.%m.%Y",
|
||||
"%d %b %Y",
|
||||
):
|
||||
try:
|
||||
return datetime.strptime(text, fmt).date(), None
|
||||
except ValueError:
|
||||
continue
|
||||
return None, f"Invalid {field_name} '{text}' (expected YYYY-MM-DD or DD-MMM-YYYY)"
|
||||
|
||||
|
||||
def _parse_optional_float(val: Any, field_name: str) -> tuple[float | None, str | None]:
|
||||
if val is None or (isinstance(val, str) and not val.strip()):
|
||||
return None, None
|
||||
if isinstance(val, (int, float)):
|
||||
if val < 0:
|
||||
return None, f"{field_name} cannot be negative"
|
||||
return float(val), None
|
||||
cleaned = re.sub(r"[₹$,\s]|(?i:rs\.?|inr)", "", str(val).strip())
|
||||
if not cleaned:
|
||||
return None, None
|
||||
try:
|
||||
parsed = float(cleaned)
|
||||
except (TypeError, ValueError):
|
||||
return None, f"Invalid {field_name} '{val}' (must be a number)"
|
||||
if parsed < 0:
|
||||
return None, f"{field_name} cannot be negative"
|
||||
return parsed, None
|
||||
|
||||
|
||||
def _parse_positive_int(val: Any, field_name: str) -> tuple[int | None, str | None]:
|
||||
if val is None or (isinstance(val, str) and not val.strip()):
|
||||
return None, f"Missing required field '{field_name}'"
|
||||
if isinstance(val, (int, float)):
|
||||
parsed = int(val)
|
||||
if parsed <= 0:
|
||||
return None, f"{field_name} must be greater than 0"
|
||||
return parsed, None
|
||||
cleaned = re.sub(r"[,\s]|(?i:months?|yrs?|years?)", "", str(val).strip())
|
||||
try:
|
||||
parsed = int(float(cleaned))
|
||||
except (TypeError, ValueError):
|
||||
return None, f"Invalid {field_name} '{val}' (must be an integer)"
|
||||
if parsed <= 0:
|
||||
return None, f"{field_name} must be greater than 0"
|
||||
return parsed, None
|
||||
|
||||
|
||||
def _extract_rows(filename: str, content: bytes, sheet_name: str | None = None) -> list[tuple[int, dict[str, Any]]]:
|
||||
ext = Path(filename or "").suffix.lower()
|
||||
if ext not in (".xlsx", ".csv", ".xls"):
|
||||
raise CodedHTTPException(
|
||||
status_code=400,
|
||||
detail="Unsupported file type. Please upload an .xlsx or .csv file.",
|
||||
code="INVALID_FILE_TYPE",
|
||||
)
|
||||
|
||||
rows_out: list[tuple[int, dict[str, Any]]] = []
|
||||
if ext in (".xlsx", ".xls"):
|
||||
try:
|
||||
wb = openpyxl.load_workbook(BytesIO(content), data_only=True)
|
||||
except Exception as exc:
|
||||
raise CodedHTTPException(
|
||||
status_code=400,
|
||||
detail="Invalid Excel file. Please download and use the import template.",
|
||||
code="INVALID_FILE_TYPE",
|
||||
) from exc
|
||||
|
||||
ws = wb.worksheets[0]
|
||||
header_cells = next(ws.iter_rows(min_row=1, max_row=1, values_only=True), None)
|
||||
if not header_cells:
|
||||
return []
|
||||
headers = [_clean_str(h).lower().replace(" ", "_").replace("-", "_") for h in header_cells]
|
||||
for row_idx, row_vals in enumerate(ws.iter_rows(min_row=2, values_only=True), start=2):
|
||||
if all(v is None or _clean_str(v) == "" for v in row_vals):
|
||||
continue
|
||||
row_dict = {
|
||||
headers[i]: (row_vals[i] if i < len(row_vals) else None)
|
||||
for i in range(len(headers))
|
||||
if headers[i]
|
||||
}
|
||||
rows_out.append((row_idx, row_dict))
|
||||
else:
|
||||
try:
|
||||
decoded = content.decode("utf-8-sig")
|
||||
except UnicodeDecodeError:
|
||||
decoded = content.decode("latin-1")
|
||||
reader = csv.reader(StringIO(decoded))
|
||||
header_row = next(reader, None)
|
||||
if not header_row:
|
||||
return []
|
||||
headers = [_clean_str(h).lower().replace(" ", "_").replace("-", "_") for h in header_row]
|
||||
for row_idx, row_vals in enumerate(reader, start=2):
|
||||
if all(_clean_str(v) == "" for v in row_vals):
|
||||
continue
|
||||
row_dict = {
|
||||
headers[i]: (row_vals[i] if i < len(row_vals) else None)
|
||||
for i in range(len(headers))
|
||||
if headers[i]
|
||||
}
|
||||
rows_out.append((row_idx, row_dict))
|
||||
return rows_out
|
||||
|
||||
|
||||
def process_contracts_import(
|
||||
db: Session,
|
||||
filename: str,
|
||||
content: bytes,
|
||||
user_id: int,
|
||||
dry_run: bool = False,
|
||||
skip_invalid: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
raw_rows = _extract_rows(filename, content, sheet_name="Contracts")
|
||||
|
||||
assets = db.query(Asset).all()
|
||||
asset_lookup: dict[str, Asset] = {a.asset_code.strip().lower(): a for a in assets if a.asset_code}
|
||||
|
||||
vendors = db.query(Vendor).filter(Vendor.is_active.is_(True)).all()
|
||||
vendor_lookup: dict[str, Vendor] = {}
|
||||
for v in vendors:
|
||||
vendor_lookup[v.name.strip().lower()] = v
|
||||
|
||||
existing_contracts = {
|
||||
(c.asset_id, (c.contract_type or "").upper(), c.start_date, c.end_date)
|
||||
for c in db.query(Contract.asset_id, Contract.contract_type, Contract.start_date, Contract.end_date).all()
|
||||
}
|
||||
seen_contracts_in_file: dict[tuple[int, str, date, date], int] = {}
|
||||
|
||||
errors: list[dict[str, Any]] = []
|
||||
preview_rows: list[dict[str, Any]] = []
|
||||
valid_records: list[dict[str, Any]] = []
|
||||
|
||||
for row_idx, row_dict in raw_rows:
|
||||
row_errors: list[str] = []
|
||||
|
||||
asset_code = _clean_str(row_dict.get("asset_code"))
|
||||
provider_name = _clean_str(
|
||||
row_dict.get("provider_name")
|
||||
or row_dict.get("vendor_name")
|
||||
or row_dict.get("provider")
|
||||
or row_dict.get("vendor")
|
||||
)
|
||||
contract_type_raw = _clean_str(row_dict.get("contract_type")).upper()
|
||||
start_date_val = row_dict.get("start_date")
|
||||
end_date_val = row_dict.get("end_date")
|
||||
cost_val = row_dict.get("contract_value")
|
||||
if cost_val is None or (isinstance(cost_val, str) and not cost_val.strip()):
|
||||
cost_val = row_dict.get("cost")
|
||||
coverage_details = _clean_str(row_dict.get("coverage_details") or row_dict.get("coverage_period_text"))
|
||||
remarks = _clean_str(row_dict.get("remarks"))
|
||||
|
||||
target_asset = None
|
||||
if not asset_code:
|
||||
row_errors.append("Missing required field 'asset_code'")
|
||||
else:
|
||||
target_asset = asset_lookup.get(asset_code.lower())
|
||||
if not target_asset:
|
||||
row_errors.append(f"Asset with code '{asset_code}' not found")
|
||||
|
||||
target_vendor = None
|
||||
if not provider_name:
|
||||
row_errors.append("Missing required field 'provider_name'")
|
||||
else:
|
||||
target_vendor = vendor_lookup.get(provider_name.lower())
|
||||
if not target_vendor:
|
||||
row_errors.append(f"Provider vendor '{provider_name}' not found")
|
||||
|
||||
if not contract_type_raw:
|
||||
row_errors.append("Missing required field 'contract_type'")
|
||||
elif contract_type_raw not in ("AMC", "CMC", "OTHER"):
|
||||
row_errors.append(f"Invalid contract_type '{contract_type_raw}' (expected AMC, CMC, or OTHER)")
|
||||
|
||||
start_date, s_err = _parse_date(start_date_val, "start_date")
|
||||
if s_err:
|
||||
row_errors.append(s_err)
|
||||
|
||||
end_date, e_err = _parse_date(end_date_val, "end_date")
|
||||
if e_err:
|
||||
row_errors.append(e_err)
|
||||
|
||||
if start_date and end_date and end_date < start_date:
|
||||
row_errors.append("end_date cannot be earlier than start_date")
|
||||
|
||||
if target_asset and contract_type_raw in ("AMC", "CMC", "OTHER") and start_date and end_date and end_date >= start_date:
|
||||
key = (target_asset.id, contract_type_raw, start_date, end_date)
|
||||
if key in seen_contracts_in_file:
|
||||
row_errors.append(f"Duplicate of row {seen_contracts_in_file[key]} in this file.")
|
||||
elif key in existing_contracts:
|
||||
row_errors.append("Already exists in the system.")
|
||||
seen_contracts_in_file[key] = row_idx
|
||||
else:
|
||||
seen_contracts_in_file[key] = row_idx
|
||||
|
||||
cost, c_err = _parse_optional_float(cost_val, "contract_value")
|
||||
if c_err:
|
||||
row_errors.append(c_err)
|
||||
|
||||
is_valid = len(row_errors) == 0
|
||||
err_text = "; ".join(row_errors) if row_errors else None
|
||||
|
||||
if not is_valid:
|
||||
errors.append({"row": row_idx, "message": err_text})
|
||||
else:
|
||||
valid_records.append({
|
||||
"asset_id": target_asset.id,
|
||||
"provider_id": target_vendor.id,
|
||||
"contract_type": contract_type_raw,
|
||||
"start_date": start_date,
|
||||
"end_date": end_date,
|
||||
"contract_value": cost,
|
||||
"coverage_period_text": coverage_details or f"{start_date} to {end_date}",
|
||||
"remarks": remarks or None,
|
||||
})
|
||||
|
||||
preview_rows.append({
|
||||
"row": row_idx,
|
||||
"data": {
|
||||
"asset_code": asset_code,
|
||||
"provider_name": provider_name,
|
||||
"contract_type": contract_type_raw,
|
||||
"start_date": str(start_date) if start_date else str(start_date_val or ""),
|
||||
"end_date": str(end_date) if end_date else str(end_date_val or ""),
|
||||
"contract_value": cost,
|
||||
"cost": cost,
|
||||
"coverage_details": coverage_details,
|
||||
"remarks": remarks,
|
||||
},
|
||||
"valid": is_valid,
|
||||
"error": err_text,
|
||||
})
|
||||
|
||||
created_count = 0
|
||||
if not dry_run:
|
||||
if errors and not skip_invalid:
|
||||
raise CodedHTTPException(
|
||||
status_code=400,
|
||||
detail=f"{len(errors)} row(s) failed validation.",
|
||||
code="IMPORT_VALIDATION_ERRORS",
|
||||
)
|
||||
if valid_records:
|
||||
for item in valid_records:
|
||||
contract = Contract(
|
||||
asset_id=item["asset_id"],
|
||||
provider_id=item["provider_id"],
|
||||
contract_type=item["contract_type"],
|
||||
start_date=item["start_date"],
|
||||
end_date=item["end_date"],
|
||||
contract_value=item["contract_value"],
|
||||
coverage_period_text=item["coverage_period_text"],
|
||||
renewed_from_id=None,
|
||||
is_superseded=False,
|
||||
remarks=item["remarks"],
|
||||
created_by_id=user_id,
|
||||
updated_by_id=user_id,
|
||||
)
|
||||
db.add(contract)
|
||||
db.flush()
|
||||
log_audit(
|
||||
db,
|
||||
entity_type="contract",
|
||||
entity_id=contract.id,
|
||||
action="create",
|
||||
changes={
|
||||
"asset_id": item["asset_id"],
|
||||
"contract_type": item["contract_type"],
|
||||
"provider_id": item["provider_id"],
|
||||
"start_date": str(item["start_date"]),
|
||||
"end_date": str(item["end_date"]),
|
||||
"source": "bulk_import",
|
||||
},
|
||||
user_id=user_id,
|
||||
)
|
||||
db.commit()
|
||||
created_count = len(valid_records)
|
||||
|
||||
return {
|
||||
"dry_run": dry_run,
|
||||
"total_rows": len(raw_rows),
|
||||
"valid_count": len(valid_records),
|
||||
"error_count": len(errors),
|
||||
"created_count": created_count,
|
||||
"errors": errors,
|
||||
"preview_rows": preview_rows,
|
||||
}
|
||||
|
||||
|
||||
def process_calibration_import(
|
||||
db: Session,
|
||||
filename: str,
|
||||
content: bytes,
|
||||
user_id: int,
|
||||
dry_run: bool = False,
|
||||
skip_invalid: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
raw_rows = _extract_rows(filename, content, sheet_name="Calibration Plans")
|
||||
|
||||
assets = db.query(Asset).all()
|
||||
asset_lookup: dict[str, Asset] = {a.asset_code.strip().lower(): a for a in assets if a.asset_code}
|
||||
|
||||
existing_plan_asset_ids = {p.asset_id for p in db.query(CalibrationPlan.asset_id).all()}
|
||||
seen_asset_ids: dict[int, int] = {}
|
||||
|
||||
vendors = db.query(Vendor).filter(Vendor.is_active.is_(True)).all()
|
||||
vendor_lookup: dict[str, Vendor] = {}
|
||||
for v in vendors:
|
||||
vendor_lookup[v.name.strip().lower()] = v
|
||||
|
||||
today = effective_today(db)
|
||||
|
||||
errors: list[dict[str, Any]] = []
|
||||
preview_rows: list[dict[str, Any]] = []
|
||||
valid_records: list[dict[str, Any]] = []
|
||||
|
||||
for row_idx, row_dict in raw_rows:
|
||||
row_errors: list[str] = []
|
||||
|
||||
asset_code = _clean_str(row_dict.get("asset_code"))
|
||||
freq_val = row_dict.get("frequency_months")
|
||||
agency_name = _clean_str(
|
||||
row_dict.get("agency_name")
|
||||
or row_dict.get("vendor_name")
|
||||
or row_dict.get("agency")
|
||||
)
|
||||
next_due_val = row_dict.get("next_due_date")
|
||||
scope = _clean_str(row_dict.get("scope"))
|
||||
standards = _clean_str(row_dict.get("standards"))
|
||||
remarks = _clean_str(row_dict.get("remarks"))
|
||||
|
||||
target_asset = None
|
||||
if not asset_code:
|
||||
row_errors.append("Missing required field 'asset_code'")
|
||||
else:
|
||||
target_asset = asset_lookup.get(asset_code.lower())
|
||||
if not target_asset:
|
||||
row_errors.append(f"Asset with code '{asset_code}' not found")
|
||||
elif target_asset.id in seen_asset_ids:
|
||||
row_errors.append(f"Duplicate of row {seen_asset_ids[target_asset.id]} in this file.")
|
||||
elif target_asset.id in existing_plan_asset_ids:
|
||||
row_errors.append("Asset already has a calibration plan.")
|
||||
seen_asset_ids[target_asset.id] = row_idx
|
||||
else:
|
||||
seen_asset_ids[target_asset.id] = row_idx
|
||||
|
||||
freq_months, f_err = _parse_positive_int(freq_val, "frequency_months")
|
||||
if f_err:
|
||||
row_errors.append(f_err)
|
||||
|
||||
target_agency = None
|
||||
if agency_name:
|
||||
target_agency = vendor_lookup.get(agency_name.lower())
|
||||
if not target_agency:
|
||||
row_errors.append(f"Calibration agency vendor '{agency_name}' not found")
|
||||
|
||||
due_date = None
|
||||
if next_due_val:
|
||||
d_parsed, d_err = _parse_date(next_due_val, "next_due_date")
|
||||
if d_err:
|
||||
row_errors.append(d_err)
|
||||
else:
|
||||
due_date = d_parsed
|
||||
elif freq_months:
|
||||
due_date = add_months(today, freq_months)
|
||||
|
||||
is_valid = len(row_errors) == 0
|
||||
err_text = "; ".join(row_errors) if row_errors else None
|
||||
|
||||
if not is_valid:
|
||||
errors.append({"row": row_idx, "message": err_text})
|
||||
else:
|
||||
valid_records.append({
|
||||
"asset": target_asset,
|
||||
"frequency_months": freq_months,
|
||||
"agency_id": target_agency.id if target_agency else None,
|
||||
"next_due_date": due_date,
|
||||
"remarks": remarks,
|
||||
})
|
||||
|
||||
preview_rows.append({
|
||||
"row": row_idx,
|
||||
"data": {
|
||||
"asset_code": asset_code,
|
||||
"frequency_months": freq_months if freq_months else freq_val,
|
||||
"agency_name": agency_name,
|
||||
"next_due_date": str(due_date) if due_date else str(next_due_val or ""),
|
||||
"scope": scope,
|
||||
"standards": standards,
|
||||
"remarks": remarks,
|
||||
},
|
||||
"valid": is_valid,
|
||||
"error": err_text,
|
||||
})
|
||||
|
||||
created_count = 0
|
||||
if not dry_run:
|
||||
if errors and not skip_invalid:
|
||||
raise CodedHTTPException(
|
||||
status_code=400,
|
||||
detail=f"{len(errors)} row(s) failed validation.",
|
||||
code="IMPORT_VALIDATION_ERRORS",
|
||||
)
|
||||
if valid_records:
|
||||
for item in valid_records:
|
||||
asset = item["asset"]
|
||||
freq = item["frequency_months"]
|
||||
agency_id = item["agency_id"]
|
||||
due_date = item["next_due_date"]
|
||||
per_year = max(1, round(12 / freq))
|
||||
|
||||
asset.requires_calibration = True
|
||||
asset.updated_by_id = user_id
|
||||
|
||||
plan = CalibrationPlan(
|
||||
asset_id=asset.id,
|
||||
frequency_months=freq,
|
||||
calibrations_per_year=per_year,
|
||||
agency_id=agency_id,
|
||||
approved_by_id=user_id,
|
||||
approved_on=today,
|
||||
next_due_date=due_date,
|
||||
is_active=True,
|
||||
created_by_id=user_id,
|
||||
updated_by_id=user_id,
|
||||
)
|
||||
db.add(plan)
|
||||
db.flush()
|
||||
|
||||
initial_rec = CalibrationRecord(
|
||||
asset_id=asset.id,
|
||||
plan_id=plan.id,
|
||||
due_date=due_date,
|
||||
agency_id=agency_id,
|
||||
status=None,
|
||||
created_by_id=user_id,
|
||||
updated_by_id=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": freq,
|
||||
"calibrations_per_year": per_year,
|
||||
"next_due_date": str(due_date),
|
||||
"approved": True,
|
||||
"initial_record_id": initial_rec.id,
|
||||
"source": "bulk_import",
|
||||
},
|
||||
user_id=user_id,
|
||||
)
|
||||
db.commit()
|
||||
created_count = len(valid_records)
|
||||
|
||||
return {
|
||||
"dry_run": dry_run,
|
||||
"total_rows": len(raw_rows),
|
||||
"valid_count": len(valid_records),
|
||||
"error_count": len(errors),
|
||||
"created_count": created_count,
|
||||
"errors": errors,
|
||||
"preview_rows": preview_rows,
|
||||
}
|
||||
|
||||
|
||||
def process_insurance_import(
|
||||
db: Session,
|
||||
filename: str,
|
||||
content: bytes,
|
||||
user_id: int,
|
||||
dry_run: bool = False,
|
||||
skip_invalid: bool = False,
|
||||
) -> dict[str, Any]:
|
||||
raw_rows = _extract_rows(filename, content, sheet_name="Insurance Policies")
|
||||
|
||||
assets = db.query(Asset).all()
|
||||
asset_lookup: dict[str, Asset] = {a.asset_code.strip().lower(): a for a in assets if a.asset_code}
|
||||
|
||||
vendors = db.query(Vendor).filter(Vendor.is_active.is_(True)).all()
|
||||
vendor_lookup: dict[str, Vendor] = {}
|
||||
for v in vendors:
|
||||
vendor_lookup[v.name.strip().lower()] = v
|
||||
|
||||
existing_policies = {
|
||||
p[0].strip().lower()
|
||||
for p in db.query(InsurancePolicy.policy_no).all()
|
||||
if p[0] and p[0].strip()
|
||||
}
|
||||
seen_policies_in_file: dict[str, int] = {}
|
||||
|
||||
errors: list[dict[str, Any]] = []
|
||||
preview_rows: list[dict[str, Any]] = []
|
||||
valid_records: list[dict[str, Any]] = []
|
||||
|
||||
for row_idx, row_dict in raw_rows:
|
||||
row_errors: list[str] = []
|
||||
|
||||
asset_code = _clean_str(row_dict.get("asset_code"))
|
||||
insurer_name = _clean_str(
|
||||
row_dict.get("insurer_name")
|
||||
or row_dict.get("vendor_name")
|
||||
or row_dict.get("insurer")
|
||||
or row_dict.get("vendor")
|
||||
)
|
||||
policy_no = _clean_str(
|
||||
row_dict.get("policy_number")
|
||||
or row_dict.get("policy_no")
|
||||
or row_dict.get("policy_num")
|
||||
)
|
||||
start_date_val = row_dict.get("start_date")
|
||||
end_date_val = row_dict.get("end_date")
|
||||
insured_val = row_dict.get("insured_value") or row_dict.get("coverage_amount")
|
||||
premium_val = row_dict.get("premium")
|
||||
remarks = _clean_str(row_dict.get("remarks"))
|
||||
|
||||
target_asset = None
|
||||
if not asset_code:
|
||||
row_errors.append("Missing required field 'asset_code'")
|
||||
else:
|
||||
target_asset = asset_lookup.get(asset_code.lower())
|
||||
if not target_asset:
|
||||
row_errors.append(f"Asset with code '{asset_code}' not found")
|
||||
|
||||
target_vendor = None
|
||||
if not insurer_name:
|
||||
row_errors.append("Missing required field 'insurer_name'")
|
||||
else:
|
||||
target_vendor = vendor_lookup.get(insurer_name.lower())
|
||||
if not target_vendor:
|
||||
row_errors.append(f"Insurer vendor '{insurer_name}' not found")
|
||||
|
||||
if not policy_no:
|
||||
row_errors.append("Missing required field 'policy_number'")
|
||||
else:
|
||||
pol_key = policy_no.strip().lower()
|
||||
if pol_key in seen_policies_in_file:
|
||||
row_errors.append(f"Duplicate of row {seen_policies_in_file[pol_key]} in this file.")
|
||||
elif pol_key in existing_policies:
|
||||
row_errors.append("Already exists in the system.")
|
||||
seen_policies_in_file[pol_key] = row_idx
|
||||
else:
|
||||
seen_policies_in_file[pol_key] = row_idx
|
||||
|
||||
start_date, s_err = _parse_date(start_date_val, "start_date")
|
||||
if s_err:
|
||||
row_errors.append(s_err)
|
||||
|
||||
end_date, e_err = _parse_date(end_date_val, "end_date")
|
||||
if e_err:
|
||||
row_errors.append(e_err)
|
||||
|
||||
if start_date and end_date and end_date < start_date:
|
||||
row_errors.append("end_date cannot be earlier than start_date")
|
||||
|
||||
coverage_amount, ca_err = _parse_optional_float(insured_val, "insured_value")
|
||||
if ca_err:
|
||||
row_errors.append(ca_err)
|
||||
|
||||
premium, p_err = _parse_optional_float(premium_val, "premium")
|
||||
if p_err:
|
||||
row_errors.append(p_err)
|
||||
|
||||
is_valid = len(row_errors) == 0
|
||||
err_text = "; ".join(row_errors) if row_errors else None
|
||||
|
||||
if not is_valid:
|
||||
errors.append({"row": row_idx, "message": err_text})
|
||||
else:
|
||||
combined_remarks = remarks
|
||||
if premium is not None and premium > 0:
|
||||
p_str = f"Premium: ₹{premium:,.2f}"
|
||||
combined_remarks = f"{remarks} ({p_str})" if remarks else p_str
|
||||
|
||||
valid_records.append({
|
||||
"asset": target_asset,
|
||||
"insurer_id": target_vendor.id,
|
||||
"policy_no": policy_no,
|
||||
"start_date": start_date,
|
||||
"end_date": end_date,
|
||||
"coverage_amount": coverage_amount,
|
||||
"remarks": combined_remarks or None,
|
||||
})
|
||||
|
||||
preview_rows.append({
|
||||
"row": row_idx,
|
||||
"data": {
|
||||
"asset_code": asset_code,
|
||||
"insurer_name": insurer_name,
|
||||
"policy_number": policy_no,
|
||||
"start_date": str(start_date) if start_date else str(start_date_val or ""),
|
||||
"end_date": str(end_date) if end_date else str(end_date_val or ""),
|
||||
"insured_value": coverage_amount,
|
||||
"premium": premium,
|
||||
"remarks": remarks,
|
||||
},
|
||||
"valid": is_valid,
|
||||
"error": err_text,
|
||||
})
|
||||
|
||||
created_count = 0
|
||||
if not dry_run:
|
||||
if errors and not skip_invalid:
|
||||
raise CodedHTTPException(
|
||||
status_code=400,
|
||||
detail=f"{len(errors)} row(s) failed validation.",
|
||||
code="IMPORT_VALIDATION_ERRORS",
|
||||
)
|
||||
if valid_records:
|
||||
for item in valid_records:
|
||||
asset = item["asset"]
|
||||
asset.insurance_applicable = True
|
||||
asset.updated_by_id = user_id
|
||||
|
||||
policy = InsurancePolicy(
|
||||
asset_id=asset.id,
|
||||
insurer_id=item["insurer_id"],
|
||||
policy_no=item["policy_no"],
|
||||
start_date=item["start_date"],
|
||||
end_date=item["end_date"],
|
||||
coverage_amount=item["coverage_amount"],
|
||||
remarks=item["remarks"],
|
||||
created_by_id=user_id,
|
||||
updated_by_id=user_id,
|
||||
)
|
||||
db.add(policy)
|
||||
db.flush()
|
||||
log_audit(
|
||||
db,
|
||||
entity_type="insurance_policy",
|
||||
entity_id=policy.id,
|
||||
action="create",
|
||||
changes={
|
||||
"asset_id": asset.id,
|
||||
"insurer_id": item["insurer_id"],
|
||||
"policy_no": item["policy_no"],
|
||||
"start_date": str(item["start_date"]),
|
||||
"end_date": str(item["end_date"]),
|
||||
"coverage_amount": item["coverage_amount"],
|
||||
"source": "bulk_import",
|
||||
},
|
||||
user_id=user_id,
|
||||
)
|
||||
db.commit()
|
||||
created_count = len(valid_records)
|
||||
|
||||
return {
|
||||
"dry_run": dry_run,
|
||||
"total_rows": len(raw_rows),
|
||||
"valid_count": len(valid_records),
|
||||
"error_count": len(errors),
|
||||
"created_count": created_count,
|
||||
"errors": errors,
|
||||
"preview_rows": preview_rows,
|
||||
}
|
||||
|
||||
@@ -0,0 +1,180 @@
|
||||
from datetime import date, datetime, time, timedelta, timezone
|
||||
from typing import Literal
|
||||
from ..core.time_utils import KOLKATA, utc_now
|
||||
|
||||
|
||||
def _ensure_utc(dt: datetime) -> datetime:
|
||||
if dt.tzinfo is None:
|
||||
return dt.replace(tzinfo=timezone.utc)
|
||||
return dt.astimezone(timezone.utc)
|
||||
|
||||
|
||||
def alert_state(
|
||||
due_date: date | None,
|
||||
today: date,
|
||||
lead_days: int,
|
||||
red_days: int,
|
||||
) -> Literal["ok", "yellow", "red"]:
|
||||
"""Classify a due date into ok/yellow/red alert severity relative to today."""
|
||||
if due_date is None:
|
||||
return "ok"
|
||||
days_left = (due_date - today).days
|
||||
if days_left <= red_days:
|
||||
return "red"
|
||||
if days_left <= lead_days:
|
||||
return "yellow"
|
||||
return "ok"
|
||||
|
||||
|
||||
def coverage_status(
|
||||
start_date: date | None,
|
||||
end_date: date | None,
|
||||
today: date,
|
||||
lead_days: int,
|
||||
red_days: int,
|
||||
) -> tuple[str, str]:
|
||||
"""Compute (status, severity) for a warranty, contract, or insurance policy."""
|
||||
if end_date is None:
|
||||
return ("none", "none")
|
||||
if end_date < today:
|
||||
return ("expired", "red")
|
||||
state = alert_state(end_date, today, lead_days, red_days)
|
||||
if state in ("yellow", "red"):
|
||||
return ("expiring", state)
|
||||
return ("active", "ok")
|
||||
|
||||
|
||||
def compute_schedule_status(
|
||||
due_date: date | None,
|
||||
persisted_status: str | None,
|
||||
today: date,
|
||||
due_window_days: int,
|
||||
red_days: int,
|
||||
) -> tuple[str, str]:
|
||||
"""Compute (status, severity) for calibration or PM records.
|
||||
|
||||
Only 'completed' or 'rescheduled' are stored in DB; upcoming/due/overdue are
|
||||
always derived dynamically against effective_today().
|
||||
"""
|
||||
if persisted_status in ("completed", "rescheduled"):
|
||||
return (persisted_status, "ok")
|
||||
if due_date is None:
|
||||
return ("none", "none")
|
||||
days_left = (due_date - today).days
|
||||
if days_left < 0:
|
||||
return ("overdue", "red")
|
||||
if days_left <= due_window_days:
|
||||
sev = "red" if days_left <= red_days else "yellow"
|
||||
return ("due", sev)
|
||||
return ("upcoming", "ok")
|
||||
|
||||
|
||||
def compute_response_time_minutes(
|
||||
registered_at: datetime,
|
||||
received_at: datetime | None,
|
||||
attended_at: datetime | None,
|
||||
response_start: str = "registered_at",
|
||||
) -> int | None:
|
||||
"""Compute response time in whole minutes from registered_at or received_at to attended_at."""
|
||||
if attended_at is None:
|
||||
return None
|
||||
reg_utc = _ensure_utc(registered_at)
|
||||
att_utc = _ensure_utc(attended_at)
|
||||
if response_start == "received_at" and received_at is not None:
|
||||
start = _ensure_utc(received_at)
|
||||
else:
|
||||
start = reg_utc
|
||||
return max(0, int((att_utc - start).total_seconds() // 60))
|
||||
|
||||
|
||||
def compute_downtime_minutes(
|
||||
registered_at: datetime,
|
||||
attended_at: datetime | None,
|
||||
restored_at: datetime | None,
|
||||
closed_at: datetime | None,
|
||||
milestone: str = "restored_at",
|
||||
now_utc: datetime | None = None,
|
||||
) -> tuple[int, bool]:
|
||||
"""Compute (downtime_minutes, is_ongoing) using the configured end milestone."""
|
||||
reg_utc = _ensure_utc(registered_at)
|
||||
end_map = {
|
||||
"attended_at": attended_at,
|
||||
"restored_at": restored_at,
|
||||
"closed_at": closed_at,
|
||||
}
|
||||
raw_end = end_map.get(milestone)
|
||||
if raw_end is None:
|
||||
is_ongoing = True
|
||||
end_dt = _ensure_utc(now_utc) if now_utc is not None else utc_now()
|
||||
else:
|
||||
is_ongoing = False
|
||||
end_dt = _ensure_utc(raw_end)
|
||||
return max(0, int((end_dt - reg_utc).total_seconds() // 60)), is_ongoing
|
||||
|
||||
|
||||
def compute_ce_response_time_minutes(
|
||||
registered_at: datetime,
|
||||
ce_attended_at: datetime | None,
|
||||
) -> int | None:
|
||||
"""Compute Company Engineer response time in whole minutes from registered_at."""
|
||||
if ce_attended_at is None:
|
||||
return None
|
||||
reg_utc = _ensure_utc(registered_at)
|
||||
ce_utc = _ensure_utc(ce_attended_at)
|
||||
return max(0, int((ce_utc - reg_utc).total_seconds() // 60))
|
||||
|
||||
|
||||
def compute_sla_status(
|
||||
priority: str,
|
||||
registered_at: datetime,
|
||||
attended_at: datetime | None,
|
||||
restored_at: datetime | None,
|
||||
critical_sla_hours: int = 4,
|
||||
non_critical_sla_hours: int = 24,
|
||||
now_utc: datetime | None = None,
|
||||
) -> tuple[bool, int]:
|
||||
"""Return (is_sla_breached, target_sla_hours) using configured SLA thresholds."""
|
||||
target_hours = critical_sla_hours if priority == "critical" else non_critical_sla_hours
|
||||
reg_utc = _ensure_utc(registered_at)
|
||||
end_ref = restored_at or attended_at
|
||||
end_utc = _ensure_utc(end_ref) if end_ref is not None else (
|
||||
_ensure_utc(now_utc) if now_utc is not None else utc_now()
|
||||
)
|
||||
elapsed_seconds = max(0.0, (end_utc - reg_utc).total_seconds())
|
||||
return elapsed_seconds > (target_hours * 3600), target_hours
|
||||
|
||||
|
||||
def clip_downtime_to_month(
|
||||
start_utc: datetime,
|
||||
end_utc: datetime,
|
||||
year: int,
|
||||
month: int,
|
||||
) -> tuple[int, set[date]]:
|
||||
"""Clip a UTC downtime interval to a calendar month in Asia/Kolkata.
|
||||
|
||||
Returns (minutes_in_month, distinct_kolkata_calendar_dates).
|
||||
"""
|
||||
win_start = KOLKATA.localize(datetime(year, month, 1, 0, 0, 0))
|
||||
next_year, next_month = (year + 1, 1) if month == 12 else (year, month + 1)
|
||||
win_end = KOLKATA.localize(datetime(next_year, next_month, 1, 0, 0, 0))
|
||||
|
||||
start_local = _ensure_utc(start_utc).astimezone(KOLKATA)
|
||||
end_local = _ensure_utc(end_utc).astimezone(KOLKATA)
|
||||
|
||||
clipped_start = max(start_local, win_start)
|
||||
clipped_end = min(end_local, win_end)
|
||||
if clipped_end <= clipped_start:
|
||||
return (0, set())
|
||||
|
||||
minutes = int((clipped_end - clipped_start).total_seconds() // 60)
|
||||
distinct_dates: set[date] = set()
|
||||
cur_day = clipped_start.date()
|
||||
last_day = clipped_end.date()
|
||||
while cur_day <= last_day:
|
||||
day_start = KOLKATA.localize(datetime.combine(cur_day, time(0, 0, 0)))
|
||||
day_end = day_start + timedelta(days=1)
|
||||
if max(clipped_start, day_start) < min(clipped_end, day_end):
|
||||
distinct_dates.add(cur_day)
|
||||
cur_day += timedelta(days=1)
|
||||
|
||||
return (minutes, distinct_dates)
|
||||
@@ -0,0 +1,257 @@
|
||||
from datetime import date
|
||||
from typing import Any, Optional
|
||||
from sqlalchemy.orm import Session, joinedload
|
||||
|
||||
from ..core.time_utils import effective_today
|
||||
from ..models import Asset, Contract, Vendor, Warranty
|
||||
from .calculations import coverage_status
|
||||
from .settings_service import get_setting_value
|
||||
|
||||
COVERAGE_TAG_LABELS: dict[str, str] = {
|
||||
"warranty": "Warranty",
|
||||
"cmc": "CMC",
|
||||
"amc": "AMC",
|
||||
"other_contract": "Other Contract",
|
||||
"out_of_contract": "Out of Contract",
|
||||
}
|
||||
|
||||
_CONTRACT_TYPE_PRIORITY = {
|
||||
"CMC": 1,
|
||||
"AMC": 2,
|
||||
"OTHER": 3,
|
||||
}
|
||||
|
||||
_CONTRACT_TYPE_TO_TAG = {
|
||||
"CMC": "cmc",
|
||||
"AMC": "amc",
|
||||
"OTHER": "other_contract",
|
||||
}
|
||||
|
||||
|
||||
def format_coverage_tag_label(tag: Optional[str]) -> str:
|
||||
if not tag:
|
||||
return "Out of Contract"
|
||||
return COVERAGE_TAG_LABELS.get(tag, tag.replace("_", " ").title())
|
||||
|
||||
|
||||
def format_vendor_contact(vendor: Optional[Vendor]) -> Optional[str]:
|
||||
if vendor is None:
|
||||
return None
|
||||
parts: list[str] = []
|
||||
if vendor.phone and vendor.phone.strip():
|
||||
parts.append(vendor.phone.strip())
|
||||
elif vendor.email and vendor.email.strip():
|
||||
parts.append(vendor.email.strip())
|
||||
if vendor.contact_person and vendor.contact_person.strip():
|
||||
if parts:
|
||||
return f"{vendor.contact_person.strip()} ({parts[0]})"
|
||||
return vendor.contact_person.strip()
|
||||
return parts[0] if parts else None
|
||||
|
||||
|
||||
def _lead_and_red_settings(db: Session) -> dict[str, int]:
|
||||
return {
|
||||
"warranty_lead": int(get_setting_value(db, "warranty_expiry_alert_days", 30)),
|
||||
"contract_lead": int(get_setting_value(db, "contract_expiry_alert_days", 30)),
|
||||
"contract_red": int(
|
||||
get_setting_value(
|
||||
db,
|
||||
"contract_critical_alert_days",
|
||||
get_setting_value(db, "red_threshold_days", 7),
|
||||
)
|
||||
),
|
||||
"red": int(get_setting_value(db, "red_threshold_days", 7)),
|
||||
}
|
||||
|
||||
|
||||
def _compute_from_records(
|
||||
warranties: list[Warranty],
|
||||
contracts: list[Contract],
|
||||
supplier: Optional[Vendor],
|
||||
on_date: date,
|
||||
leads: dict[str, int],
|
||||
) -> dict[str, Any]:
|
||||
# 1. Active warranties: start_date <= on_date <= end_date
|
||||
active_warranties = [
|
||||
w for w in warranties if w.start_date <= on_date <= w.end_date
|
||||
]
|
||||
if active_warranties:
|
||||
active_warranties.sort(key=lambda w: (w.end_date, w.id), reverse=True)
|
||||
w = active_warranties[0]
|
||||
provider = w.provider or supplier
|
||||
_, sev = coverage_status(
|
||||
w.start_date, w.end_date, on_date, leads["warranty_lead"], leads["red"]
|
||||
)
|
||||
sev_norm = sev if sev in ("ok", "yellow", "red") else "ok"
|
||||
return {
|
||||
"tag": "warranty",
|
||||
"contract_id": None,
|
||||
"warranty_id": w.id,
|
||||
"provider_id": provider.id if provider else w.provider_id,
|
||||
"provider_name": provider.name if provider else None,
|
||||
"provider_contact": format_vendor_contact(provider),
|
||||
"valid_from": w.start_date,
|
||||
"valid_until": w.end_date,
|
||||
"days_left": (w.end_date - on_date).days,
|
||||
"severity": sev_norm,
|
||||
}
|
||||
|
||||
# 2. Active non-superseded contracts: priority CMC > AMC > OTHER
|
||||
active_contracts = [
|
||||
c
|
||||
for c in contracts
|
||||
if not c.is_superseded and c.start_date <= on_date <= c.end_date
|
||||
]
|
||||
if active_contracts:
|
||||
active_contracts.sort(
|
||||
key=lambda c: (
|
||||
_CONTRACT_TYPE_PRIORITY.get((c.contract_type or "").upper(), 99),
|
||||
-c.end_date.toordinal(),
|
||||
-c.id,
|
||||
)
|
||||
)
|
||||
c = active_contracts[0]
|
||||
ctype = (c.contract_type or "OTHER").upper()
|
||||
tag = _CONTRACT_TYPE_TO_TAG.get(ctype, "other_contract")
|
||||
provider = c.provider
|
||||
_, sev = coverage_status(
|
||||
c.start_date, c.end_date, on_date, leads["contract_lead"], leads["contract_red"]
|
||||
)
|
||||
sev_norm = sev if sev in ("ok", "yellow", "red") else "ok"
|
||||
return {
|
||||
"tag": tag,
|
||||
"contract_id": c.id,
|
||||
"warranty_id": None,
|
||||
"provider_id": c.provider_id,
|
||||
"provider_name": provider.name if provider else None,
|
||||
"provider_contact": format_vendor_contact(provider),
|
||||
"valid_from": c.start_date,
|
||||
"valid_until": c.end_date,
|
||||
"days_left": (c.end_date - on_date).days,
|
||||
"severity": sev_norm,
|
||||
}
|
||||
|
||||
# 3. Out of contract
|
||||
return {
|
||||
"tag": "out_of_contract",
|
||||
"contract_id": None,
|
||||
"warranty_id": None,
|
||||
"provider_id": None,
|
||||
"provider_name": None,
|
||||
"provider_contact": None,
|
||||
"valid_from": None,
|
||||
"valid_until": None,
|
||||
"days_left": None,
|
||||
"severity": "red",
|
||||
}
|
||||
|
||||
|
||||
def get_coverage(
|
||||
db: Session,
|
||||
asset_id: int,
|
||||
on_date: Optional[date] = None,
|
||||
) -> dict[str, Any]:
|
||||
target_date = on_date or effective_today(db)
|
||||
leads = _lead_and_red_settings(db)
|
||||
|
||||
asset = (
|
||||
db.query(Asset)
|
||||
.options(joinedload(Asset.supplier))
|
||||
.filter(Asset.id == asset_id)
|
||||
.first()
|
||||
)
|
||||
supplier = asset.supplier if asset else None
|
||||
|
||||
warranties = (
|
||||
db.query(Warranty)
|
||||
.options(joinedload(Warranty.provider))
|
||||
.filter(Warranty.asset_id == asset_id)
|
||||
.all()
|
||||
)
|
||||
contracts = (
|
||||
db.query(Contract)
|
||||
.options(joinedload(Contract.provider))
|
||||
.filter(Contract.asset_id == asset_id, Contract.is_superseded.is_(False))
|
||||
.all()
|
||||
)
|
||||
return _compute_from_records(warranties, contracts, supplier, target_date, leads)
|
||||
|
||||
|
||||
def get_coverage_map(
|
||||
db: Session,
|
||||
asset_ids: list[int],
|
||||
on_date: Optional[date] = None,
|
||||
) -> dict[int, dict[str, Any]]:
|
||||
if not asset_ids:
|
||||
return {}
|
||||
unique_ids = list(set(asset_ids))
|
||||
target_date = on_date or effective_today(db)
|
||||
leads = _lead_and_red_settings(db)
|
||||
|
||||
assets = (
|
||||
db.query(Asset)
|
||||
.options(joinedload(Asset.supplier))
|
||||
.filter(Asset.id.in_(unique_ids))
|
||||
.all()
|
||||
)
|
||||
supplier_by_asset: dict[int, Optional[Vendor]] = {a.id: a.supplier for a in assets}
|
||||
|
||||
warranties_by_asset: dict[int, list[Warranty]] = {aid: [] for aid in unique_ids}
|
||||
for w in (
|
||||
db.query(Warranty)
|
||||
.options(joinedload(Warranty.provider))
|
||||
.filter(Warranty.asset_id.in_(unique_ids))
|
||||
.all()
|
||||
):
|
||||
warranties_by_asset.setdefault(w.asset_id, []).append(w)
|
||||
|
||||
contracts_by_asset: dict[int, list[Contract]] = {aid: [] for aid in unique_ids}
|
||||
for c in (
|
||||
db.query(Contract)
|
||||
.options(joinedload(Contract.provider))
|
||||
.filter(Contract.asset_id.in_(unique_ids), Contract.is_superseded.is_(False))
|
||||
.all()
|
||||
):
|
||||
contracts_by_asset.setdefault(c.asset_id, []).append(c)
|
||||
|
||||
return {
|
||||
aid: _compute_from_records(
|
||||
warranties_by_asset.get(aid, []),
|
||||
contracts_by_asset.get(aid, []),
|
||||
supplier_by_asset.get(aid),
|
||||
target_date,
|
||||
leads,
|
||||
)
|
||||
for aid in unique_ids
|
||||
}
|
||||
|
||||
|
||||
def get_active_amc_cmc(
|
||||
db: Session,
|
||||
asset_id: int,
|
||||
on_date: Optional[date] = None,
|
||||
) -> Optional[Contract]:
|
||||
"""Return the highest-priority active non-superseded AMC/CMC contract (CMC > AMC)."""
|
||||
target_date = on_date or effective_today(db)
|
||||
contracts = (
|
||||
db.query(Contract)
|
||||
.filter(
|
||||
Contract.asset_id == asset_id,
|
||||
Contract.is_superseded.is_(False),
|
||||
Contract.contract_type.in_(["CMC", "AMC"]),
|
||||
Contract.start_date <= target_date,
|
||||
Contract.end_date >= target_date,
|
||||
)
|
||||
.all()
|
||||
)
|
||||
if not contracts:
|
||||
return None
|
||||
contracts.sort(
|
||||
key=lambda c: (
|
||||
_CONTRACT_TYPE_PRIORITY.get((c.contract_type or "").upper(), 99),
|
||||
-c.end_date.toordinal(),
|
||||
-c.id,
|
||||
)
|
||||
)
|
||||
return contracts[0]
|
||||
|
||||
@@ -0,0 +1,346 @@
|
||||
import csv
|
||||
from io import BytesIO, StringIO
|
||||
import re
|
||||
from typing import Any
|
||||
from openpyxl import Workbook
|
||||
from openpyxl.styles import Alignment, Border, Font, PatternFill, Side
|
||||
from openpyxl.utils import get_column_letter
|
||||
|
||||
from ..core.time_utils import format_datetime, utc_now
|
||||
|
||||
|
||||
def _sanitize_sheet_title(title: str) -> str:
|
||||
"""Sanitize Excel sheet title to comply with openpyxl / Excel naming rules."""
|
||||
cleaned = re.sub(r'[\\/*?:\[\]]', '_', title or "Report").strip()
|
||||
return cleaned[:31] or "Report"
|
||||
|
||||
|
||||
def _format_filters_echo(filters_applied: dict[str, Any]) -> str:
|
||||
if not filters_applied:
|
||||
return "None"
|
||||
return ", ".join(f"{k}={v}" for k, v in filters_applied.items())
|
||||
|
||||
|
||||
def _format_summary_echo(summary: dict[str, Any]) -> str:
|
||||
if not summary:
|
||||
return ""
|
||||
return " | ".join(f"{k.replace('_', ' ').title()}: {v}" for k, v in summary.items())
|
||||
|
||||
|
||||
# Styling constants for executive Excel reports
|
||||
_NAVY_HEADER_FILL = PatternFill(start_color="1E3A8A", end_color="1E3A8A", fill_type="solid")
|
||||
_ZEBRA_FILL = PatternFill(start_color="F8FAFC", end_color="F8FAFC", fill_type="solid")
|
||||
_WHITE_FILL = PatternFill(start_color="FFFFFF", end_color="FFFFFF", fill_type="solid")
|
||||
_SUMMARY_FILL = PatternFill(start_color="EFF6FF", end_color="EFF6FF", fill_type="solid")
|
||||
_TOTAL_FILL = PatternFill(start_color="F1F5F9", end_color="F1F5F9", fill_type="solid")
|
||||
|
||||
_TITLE_FONT = Font(name="Calibri", size=14, bold=True, color="0F172A")
|
||||
_META_FONT = Font(name="Calibri", size=9, italic=True, color="475569")
|
||||
_SUMMARY_FONT = Font(name="Calibri", size=10, bold=True, color="1E3A8A")
|
||||
_HEADER_FONT = Font(name="Calibri", size=11, bold=True, color="FFFFFF")
|
||||
_DATA_FONT = Font(name="Calibri", size=10, color="0F172A")
|
||||
_TOTAL_FONT = Font(name="Calibri", size=10, bold=True, color="1E3A8A")
|
||||
|
||||
_THIN_SIDE = Side(style="thin", color="CBD5E1")
|
||||
_CELL_BORDER = Border(left=_THIN_SIDE, right=_THIN_SIDE, top=_THIN_SIDE, bottom=_THIN_SIDE)
|
||||
_HEADER_BORDER = Border(
|
||||
left=Side(style="thin", color="334155"),
|
||||
right=Side(style="thin", color="334155"),
|
||||
top=Side(style="thin", color="334155"),
|
||||
bottom=Side(style="medium", color="0F172A"),
|
||||
)
|
||||
_TOTAL_BORDER = Border(
|
||||
left=_THIN_SIDE,
|
||||
right=_THIN_SIDE,
|
||||
top=Side(style="thin", color="94A3B8"),
|
||||
bottom=Side(style="double", color="1E3A8A"),
|
||||
)
|
||||
|
||||
|
||||
def _detect_cell_format(col_key: str, col_label: str, val: Any) -> tuple[Alignment, str | None]:
|
||||
"""Determine alignment and Excel number format from column metadata and value."""
|
||||
key_lower = col_key.lower()
|
||||
lbl_lower = col_label.lower()
|
||||
|
||||
# Currency / Financial costs
|
||||
if any(k in key_lower or k in lbl_lower for k in ["cost", "value", "price", "amount", "budget", "estimate"]):
|
||||
align = Alignment(horizontal="right", vertical="center")
|
||||
num_fmt = '"₹"#,##0.00' if isinstance(val, float) else '"₹"#,##0'
|
||||
return align, num_fmt
|
||||
|
||||
# Percentages
|
||||
if any(k in key_lower or k in lbl_lower for k in ["pct", "percent", "rate", "uptime"]):
|
||||
align = Alignment(horizontal="right", vertical="center")
|
||||
num_fmt = '0.0"%"' if isinstance(val, (int, float)) else None
|
||||
return align, num_fmt
|
||||
|
||||
# Numeric counts / durations / minutes
|
||||
if isinstance(val, (int, float)) and not isinstance(val, bool):
|
||||
align = Alignment(horizontal="right", vertical="center")
|
||||
num_fmt = "#,##0" if isinstance(val, int) else "#,##0.0"
|
||||
return align, num_fmt
|
||||
|
||||
# Dates, codes, status, IDs, booleans
|
||||
if any(k in key_lower or k in lbl_lower for k in ["date", "code", "no", "status", "priority", "criticality", "mode"]):
|
||||
align = Alignment(horizontal="center", vertical="center")
|
||||
return align, None
|
||||
|
||||
# Text / Names / Descriptions
|
||||
align = Alignment(horizontal="left", vertical="center")
|
||||
return align, None
|
||||
|
||||
|
||||
def _write_styled_sheet(ws, report_payload: dict[str, Any]) -> None:
|
||||
# Explicitly show grid lines in Excel view
|
||||
ws.views.sheetView[0].showGridLines = True
|
||||
|
||||
title_text = f"Poona Hospital & Research Centre \u2014 {report_payload['title']}"
|
||||
meta_text = (
|
||||
f"Generated: {format_datetime(utc_now())} IST | "
|
||||
f"Filters: {_format_filters_echo(report_payload.get('filters_applied', {}))}"
|
||||
)
|
||||
summary_text = _format_summary_echo(report_payload.get("summary", {}))
|
||||
|
||||
# Row 1: Hospital Title
|
||||
ws.row_dimensions[1].height = 28
|
||||
c1 = ws.cell(row=1, column=1, value=title_text)
|
||||
c1.font = _TITLE_FONT
|
||||
c1.alignment = Alignment(vertical="center")
|
||||
|
||||
# Row 2: Metadata & Filters
|
||||
ws.row_dimensions[2].height = 18
|
||||
c2 = ws.cell(row=2, column=1, value=meta_text)
|
||||
c2.font = _META_FONT
|
||||
c2.alignment = Alignment(vertical="center")
|
||||
|
||||
# Row 3: Summary KPIs strip
|
||||
ws.row_dimensions[3].height = 24
|
||||
c3 = ws.cell(row=3, column=1, value=summary_text)
|
||||
c3.font = _SUMMARY_FONT
|
||||
c3.fill = _SUMMARY_FILL
|
||||
c3.border = Border(
|
||||
top=Side(style="thin", color="BFDBFE"),
|
||||
bottom=Side(style="thin", color="BFDBFE"),
|
||||
left=Side(style="thin", color="BFDBFE"),
|
||||
right=Side(style="thin", color="BFDBFE"),
|
||||
)
|
||||
c3.alignment = Alignment(vertical="center", indent=1)
|
||||
|
||||
# Row 4: Spacer
|
||||
ws.row_dimensions[4].height = 10
|
||||
|
||||
columns: list[dict[str, str]] = report_payload.get("columns", [])
|
||||
rows: list[dict[str, Any]] = report_payload.get("rows", [])
|
||||
|
||||
# Span summary strip styling across header columns
|
||||
if columns and len(columns) > 1:
|
||||
for c_idx in range(2, len(columns) + 1):
|
||||
sc = ws.cell(row=3, column=c_idx)
|
||||
sc.fill = _SUMMARY_FILL
|
||||
sc.border = Border(
|
||||
top=Side(style="thin", color="BFDBFE"),
|
||||
bottom=Side(style="thin", color="BFDBFE"),
|
||||
left=Side(style="thin", color="BFDBFE"),
|
||||
right=Side(style="thin", color="BFDBFE"),
|
||||
)
|
||||
|
||||
header_row = 5
|
||||
ws.row_dimensions[header_row].height = 28
|
||||
col_widths: list[int] = []
|
||||
|
||||
for c_idx, col in enumerate(columns, start=1):
|
||||
cell = ws.cell(row=header_row, column=c_idx, value=col["label"])
|
||||
cell.fill = _NAVY_HEADER_FILL
|
||||
cell.font = _HEADER_FONT
|
||||
cell.alignment = Alignment(horizontal="center", vertical="center", wrap_text=True)
|
||||
cell.border = _HEADER_BORDER
|
||||
col_widths.append(len(str(col["label"])))
|
||||
|
||||
# Freeze header panes
|
||||
ws.freeze_panes = "A6"
|
||||
|
||||
# Data rows
|
||||
last_data_row = header_row
|
||||
for r_offset, row_data in enumerate(rows):
|
||||
excel_row = header_row + 1 + r_offset
|
||||
last_data_row = excel_row
|
||||
ws.row_dimensions[excel_row].height = 20
|
||||
row_fill = _ZEBRA_FILL if r_offset % 2 == 1 else _WHITE_FILL
|
||||
|
||||
for c_idx, col in enumerate(columns, start=1):
|
||||
val = row_data.get(col["key"])
|
||||
if isinstance(val, bool):
|
||||
val = "Yes" if val else "No"
|
||||
|
||||
cell = ws.cell(row=excel_row, column=c_idx, value=val)
|
||||
cell.fill = row_fill
|
||||
cell.font = _DATA_FONT
|
||||
cell.border = _CELL_BORDER
|
||||
|
||||
align, num_fmt = _detect_cell_format(col["key"], col["label"], val)
|
||||
cell.alignment = align
|
||||
if num_fmt and isinstance(val, (int, float)):
|
||||
cell.number_format = num_fmt
|
||||
|
||||
val_len = len(str(val)) if val is not None else 0
|
||||
if val_len > col_widths[c_idx - 1]:
|
||||
col_widths[c_idx - 1] = val_len
|
||||
|
||||
# Add native Excel AutoFilter on header row
|
||||
if columns:
|
||||
last_col_letter = get_column_letter(len(columns))
|
||||
ws.auto_filter.ref = f"A{header_row}:{last_col_letter}{last_data_row}"
|
||||
|
||||
# Total summary row at bottom
|
||||
if rows:
|
||||
summary_row = last_data_row + 1
|
||||
ws.row_dimensions[summary_row].height = 22
|
||||
for c_idx in range(1, len(columns) + 1):
|
||||
tot_cell = ws.cell(row=summary_row, column=c_idx)
|
||||
tot_cell.fill = _TOTAL_FILL
|
||||
tot_cell.border = _TOTAL_BORDER
|
||||
tot_cell.font = _TOTAL_FONT
|
||||
if c_idx == 1:
|
||||
tot_cell.value = f"Total Records: {len(rows)}"
|
||||
tot_cell.alignment = Alignment(horizontal="left", vertical="center")
|
||||
else:
|
||||
tot_cell.alignment = Alignment(horizontal="center", vertical="center")
|
||||
|
||||
for c_idx, width in enumerate(col_widths, start=1):
|
||||
ws.column_dimensions[get_column_letter(c_idx)].width = min(50, max(14, width + 4))
|
||||
|
||||
# Pre-configure page setup for professional A4 Landscape printing / PDF conversion from Excel
|
||||
try:
|
||||
ws.page_setup.orientation = ws.ORIENTATION_LANDSCAPE
|
||||
ws.page_setup.paperSize = ws.PAPERSIZE_A4
|
||||
ws.page_setup.fitToPage = True
|
||||
ws.page_setup.fitToWidth = 1
|
||||
ws.page_setup.fitToHeight = 0
|
||||
ws.sheet_properties.pageSetUpPr.fitToPage = True
|
||||
ws.print_title_rows = f"{header_row}:{header_row}"
|
||||
ws.oddHeader.left.text = "&BPoona Hospital & Research Centre&B"
|
||||
ws.oddHeader.right.text = report_payload.get("title", "Operational Report")
|
||||
ws.oddFooter.left.text = "Confidential • Biomedical Asset Management System"
|
||||
ws.oddFooter.right.text = "Page &P of &N"
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def build_xlsx(report_payload: dict[str, Any]) -> BytesIO:
|
||||
wb = Workbook()
|
||||
ws = wb.active
|
||||
ws.title = _sanitize_sheet_title(report_payload.get("title", "Report"))
|
||||
_write_styled_sheet(ws, report_payload)
|
||||
|
||||
buf = BytesIO()
|
||||
wb.save(buf)
|
||||
buf.seek(0)
|
||||
return buf
|
||||
|
||||
|
||||
def build_ai_xlsx(
|
||||
report_payload: dict[str, Any],
|
||||
evidence: list[dict[str, Any]],
|
||||
how_calculated: dict[str, Any],
|
||||
) -> BytesIO:
|
||||
"""Build a styled 3-sheet AI report workbook: main report, Evidence, and How calculated."""
|
||||
wb = Workbook()
|
||||
|
||||
# Sheet 1: Main report
|
||||
ws_main = wb.active
|
||||
ws_main.title = _sanitize_sheet_title(report_payload.get("title", "AI Report"))
|
||||
_write_styled_sheet(ws_main, report_payload)
|
||||
|
||||
# Sheet 2: Evidence
|
||||
ws_ev = wb.create_sheet(title=_sanitize_sheet_title("Evidence"))
|
||||
ev_payload = {
|
||||
"title": f"{report_payload.get('title', 'AI Report')} — Evidence",
|
||||
"filters_applied": report_payload.get("filters_applied", {}),
|
||||
"summary": {"evidence_metrics": len(evidence)},
|
||||
"columns": [
|
||||
{"key": "id", "label": "Metric ID"},
|
||||
{"key": "label", "label": "Label"},
|
||||
{"key": "value", "label": "Raw Value"},
|
||||
{"key": "unit", "label": "Unit"},
|
||||
{"key": "formatted", "label": "Formatted"},
|
||||
],
|
||||
"rows": [
|
||||
{
|
||||
"id": m.get("id", ""),
|
||||
"label": m.get("label", ""),
|
||||
"value": m.get("value"),
|
||||
"unit": m.get("unit", ""),
|
||||
"formatted": m.get("formatted", ""),
|
||||
}
|
||||
for m in (evidence or [])
|
||||
],
|
||||
}
|
||||
_write_styled_sheet(ws_ev, ev_payload)
|
||||
|
||||
# Sheet 3: How calculated
|
||||
ws_how = wb.create_sheet(title=_sanitize_sheet_title("How calculated"))
|
||||
how_rows: list[dict[str, Any]] = []
|
||||
for idx, formula in enumerate((how_calculated or {}).get("formulas", []), start=1):
|
||||
how_rows.append({"item": f"Formula {idx}", "details": str(formula)})
|
||||
if (how_calculated or {}).get("latest_equipment_rule"):
|
||||
how_rows.append({"item": "Latest Equipment Rule", "details": str(how_calculated["latest_equipment_rule"])})
|
||||
if (how_calculated or {}).get("missing_data_rule"):
|
||||
how_rows.append({"item": "Missing Data Rule", "details": str(how_calculated["missing_data_rule"])})
|
||||
for k, v in ((how_calculated or {}).get("weights") or {}).items():
|
||||
how_rows.append({"item": f"Weight: {k}", "details": str(v)})
|
||||
for k, v in ((how_calculated or {}).get("settings_used") or {}).items():
|
||||
how_rows.append({"item": f"Setting: {k}", "details": str(v)})
|
||||
if not how_rows:
|
||||
how_rows.append({"item": "Method", "details": "Deterministic Python calculations on hospital AMS data."})
|
||||
|
||||
how_payload = {
|
||||
"title": f"{report_payload.get('title', 'AI Report')} — How Calculated",
|
||||
"filters_applied": report_payload.get("filters_applied", {}),
|
||||
"summary": {"items": len(how_rows)},
|
||||
"columns": [
|
||||
{"key": "item", "label": "Item"},
|
||||
{"key": "details", "label": "Formula / Parameter Details"},
|
||||
],
|
||||
"rows": how_rows,
|
||||
}
|
||||
_write_styled_sheet(ws_how, how_payload)
|
||||
|
||||
buf = BytesIO()
|
||||
wb.save(buf)
|
||||
buf.seek(0)
|
||||
return buf
|
||||
|
||||
|
||||
def build_csv(report_payload: dict[str, Any]) -> BytesIO:
|
||||
sio = StringIO()
|
||||
writer = csv.writer(sio)
|
||||
|
||||
writer.writerow([f"Poona Hospital & Research Centre - {report_payload['title']}"])
|
||||
writer.writerow(
|
||||
[
|
||||
f"Generated: {format_datetime(utc_now())} IST",
|
||||
f"Filters: {_format_filters_echo(report_payload.get('filters_applied', {}))}",
|
||||
]
|
||||
)
|
||||
summary_text = _format_summary_echo(report_payload.get("summary", {}))
|
||||
if summary_text:
|
||||
writer.writerow([f"Summary: {summary_text}"])
|
||||
writer.writerow([])
|
||||
|
||||
columns: list[dict[str, str]] = report_payload.get("columns", [])
|
||||
rows: list[dict[str, Any]] = report_payload.get("rows", [])
|
||||
|
||||
writer.writerow([col["label"] for col in columns])
|
||||
for row_data in rows:
|
||||
out_row = []
|
||||
for col in columns:
|
||||
val = row_data.get(col["key"])
|
||||
if isinstance(val, bool):
|
||||
val = "Yes" if val else "No"
|
||||
out_row.append("" if val is None else val)
|
||||
writer.writerow(out_row)
|
||||
|
||||
data = sio.getvalue().encode("utf-8-sig")
|
||||
buf = BytesIO(data)
|
||||
buf.seek(0)
|
||||
return buf
|
||||
@@ -0,0 +1,24 @@
|
||||
from datetime import datetime, timezone
|
||||
from sqlalchemy.orm import Session
|
||||
from ..core.time_utils import to_kolkata
|
||||
from ..models.complaints import Complaint
|
||||
|
||||
|
||||
def generate_complaint_no(db: Session, prefix: str, dt_utc: datetime) -> str:
|
||||
dt_aware = dt_utc if dt_utc.tzinfo else dt_utc.replace(tzinfo=timezone.utc)
|
||||
year = to_kolkata(dt_aware).year
|
||||
base = f"{prefix}-{year}-"
|
||||
existing = (
|
||||
db.query(Complaint.complaint_no)
|
||||
.filter(Complaint.complaint_no.like(f"{base}%"))
|
||||
.all()
|
||||
)
|
||||
max_seq = 0
|
||||
for (cno,) in existing:
|
||||
if cno and cno.startswith(base):
|
||||
suffix = cno[len(base) :]
|
||||
if suffix.isdigit():
|
||||
val = int(suffix)
|
||||
if val > max_seq:
|
||||
max_seq = val
|
||||
return f"{base}{max_seq + 1:04d}"
|
||||
@@ -0,0 +1,141 @@
|
||||
from enum import Enum
|
||||
from typing import Any
|
||||
from fastapi.encoders import jsonable_encoder
|
||||
from fastapi.responses import JSONResponse
|
||||
|
||||
|
||||
class Role(str, Enum):
|
||||
system_admin = "system_admin"
|
||||
biomedical = "biomedical"
|
||||
department_user = "department_user"
|
||||
management = "management"
|
||||
coordinator = "coordinator"
|
||||
|
||||
|
||||
ALL_ROLES: set[str] = {r.value for r in Role}
|
||||
|
||||
RESTRICTED_COMPLAINT_FIELDS: set[str] = {
|
||||
"action_taken",
|
||||
"root_cause",
|
||||
"corrective_action",
|
||||
"lessons_learned",
|
||||
"ce_name",
|
||||
"ce_attended_at",
|
||||
"ce_action_taken",
|
||||
"spare_required",
|
||||
"spare_details",
|
||||
"spare_cost_estimate",
|
||||
"repair_cost",
|
||||
}
|
||||
|
||||
COST_FIELDS: set[str] = {
|
||||
"purchase_value",
|
||||
"monthly_rent",
|
||||
"contract_value",
|
||||
"cost_per_visit",
|
||||
"repair_cost",
|
||||
"spare_cost_estimate",
|
||||
}
|
||||
|
||||
CAPABILITIES: dict[Role, set[str]] = {
|
||||
Role.system_admin: {
|
||||
"manage_admin",
|
||||
"create_edit_assets",
|
||||
"edit_asset_contracts_only",
|
||||
"view_assets",
|
||||
"raise_complaint",
|
||||
"handle_complaint",
|
||||
"edit_technical_fields",
|
||||
"manage_pm",
|
||||
"view_pm",
|
||||
"manage_calibration_contracts",
|
||||
"view_calibration_contracts",
|
||||
"manage_demo_equipment",
|
||||
"view_demo_equipment",
|
||||
"manage_visits",
|
||||
"view_visits",
|
||||
"view_all_reports",
|
||||
"view_dept_reports",
|
||||
"view_ai_reports",
|
||||
"view_costs",
|
||||
},
|
||||
Role.biomedical: {
|
||||
"create_edit_assets",
|
||||
"view_assets",
|
||||
"raise_complaint",
|
||||
"handle_complaint",
|
||||
"edit_technical_fields",
|
||||
"manage_pm",
|
||||
"view_pm",
|
||||
"manage_calibration_contracts",
|
||||
"view_calibration_contracts",
|
||||
"manage_demo_equipment",
|
||||
"view_demo_equipment",
|
||||
"manage_visits",
|
||||
"view_visits",
|
||||
"view_all_reports",
|
||||
"view_dept_reports",
|
||||
"view_ai_reports",
|
||||
"view_costs",
|
||||
},
|
||||
Role.department_user: {
|
||||
"view_assets",
|
||||
"raise_complaint",
|
||||
"view_pm",
|
||||
"view_calibration_contracts",
|
||||
"view_demo_equipment",
|
||||
"view_dept_reports",
|
||||
},
|
||||
Role.management: {
|
||||
"view_assets",
|
||||
"view_pm",
|
||||
"view_calibration_contracts",
|
||||
"view_demo_equipment",
|
||||
"view_visits",
|
||||
"view_all_reports",
|
||||
"view_dept_reports",
|
||||
"view_ai_reports",
|
||||
"view_costs",
|
||||
},
|
||||
Role.coordinator: {
|
||||
"edit_asset_contracts_only",
|
||||
"view_assets",
|
||||
"handle_complaint",
|
||||
"view_pm",
|
||||
"manage_calibration_contracts",
|
||||
"view_calibration_contracts",
|
||||
"manage_demo_equipment",
|
||||
"view_demo_equipment",
|
||||
"view_all_reports",
|
||||
"view_dept_reports",
|
||||
"view_ai_reports",
|
||||
"view_costs",
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
def has_capability(role: Role | str | None, capability: str) -> bool:
|
||||
if role is None:
|
||||
return False
|
||||
try:
|
||||
role_enum = role if isinstance(role, Role) else Role(role)
|
||||
except ValueError:
|
||||
return False
|
||||
return capability in CAPABILITIES.get(role_enum, set())
|
||||
|
||||
|
||||
def strip_cost_fields(data: Any) -> Any:
|
||||
"""Recursively remove cost keys from serialized JSON payloads for restricted roles."""
|
||||
if isinstance(data, dict):
|
||||
return {k: strip_cost_fields(v) for k, v in data.items() if k not in COST_FIELDS}
|
||||
if isinstance(data, list):
|
||||
return [strip_cost_fields(item) for item in data]
|
||||
return data
|
||||
|
||||
|
||||
def maybe_strip_costs_response(payload: Any, role: Role | str | None, status_code: int = 200) -> Any:
|
||||
"""Return payload unchanged if role can view costs; otherwise return JSONResponse with cost fields stripped."""
|
||||
if has_capability(role, "view_costs"):
|
||||
return payload
|
||||
encoded = jsonable_encoder(payload)
|
||||
return JSONResponse(content=strip_cost_fields(encoded), status_code=status_code)
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,45 @@
|
||||
from dataclasses import dataclass
|
||||
from typing import Optional
|
||||
|
||||
from ..models import User
|
||||
from .permissions import Role
|
||||
|
||||
|
||||
@dataclass
|
||||
class DepartmentScope:
|
||||
is_unconstrained: bool
|
||||
department_id: Optional[int]
|
||||
is_empty: bool
|
||||
|
||||
|
||||
def resolve_department_scope(
|
||||
user: User,
|
||||
requested_dept_id: Optional[int] = None,
|
||||
) -> DepartmentScope:
|
||||
"""Resolve department scoping based on user role and assigned department.
|
||||
|
||||
Rules:
|
||||
- If user.role != 'department_user': unconstrained, department_id=requested_dept_id, is_empty=False.
|
||||
- If user.role == 'department_user' and user.department_id is None: is_empty=True, department_id=None, is_unconstrained=False.
|
||||
- If user.role == 'department_user' and user.department_id is not None: is_empty=False, department_id=user.department_id
|
||||
(requested_dept_id is ignored, cannot widen or change), is_unconstrained=False.
|
||||
"""
|
||||
if user.role != Role.department_user.value:
|
||||
return DepartmentScope(
|
||||
is_unconstrained=True,
|
||||
department_id=requested_dept_id,
|
||||
is_empty=False,
|
||||
)
|
||||
|
||||
if user.department_id is None:
|
||||
return DepartmentScope(
|
||||
is_unconstrained=False,
|
||||
department_id=None,
|
||||
is_empty=True,
|
||||
)
|
||||
|
||||
return DepartmentScope(
|
||||
is_unconstrained=False,
|
||||
department_id=user.department_id,
|
||||
is_empty=False,
|
||||
)
|
||||
@@ -0,0 +1,566 @@
|
||||
import json
|
||||
from datetime import date
|
||||
from typing import Any
|
||||
from fastapi import HTTPException, status
|
||||
from sqlalchemy.orm import Session
|
||||
from ..core.time_utils import utc_now
|
||||
from ..models.masters import Setting
|
||||
|
||||
SETTINGS_SCHEMA: list[dict[str, Any]] = [
|
||||
{
|
||||
"key": "demo_as_of_date",
|
||||
"type": "date_or_empty",
|
||||
"default": "",
|
||||
"label": "Demo As-Of Date",
|
||||
"description": "Optional YYYY-MM-DD override for the system clock (used for testing/demos). Leave empty for real Asia/Kolkata date.",
|
||||
"min": None,
|
||||
"max": None,
|
||||
"options": None,
|
||||
},
|
||||
{
|
||||
"key": "contract_expiry_alert_days",
|
||||
"type": "int",
|
||||
"default": 30,
|
||||
"label": "Contract Expiry Alert Lead Days",
|
||||
"description": "Days prior to AMC/CMC/OTHER contract end date to generate expiry alerts.",
|
||||
"min": 1,
|
||||
"max": 180,
|
||||
"options": None,
|
||||
},
|
||||
{
|
||||
"key": "contract_critical_alert_days",
|
||||
"type": "int",
|
||||
"default": 7,
|
||||
"label": "Contract Critical Expiry Alert Days",
|
||||
"description": "Days prior to contract expiry to escalate alert severity to critical (red).",
|
||||
"min": 1,
|
||||
"max": 60,
|
||||
"options": None,
|
||||
},
|
||||
{
|
||||
"key": "warranty_expiry_alert_days",
|
||||
"type": "int",
|
||||
"default": 30,
|
||||
"label": "Warranty Expiry Alert Lead Days",
|
||||
"description": "Days prior to warranty end date to trigger expiry alerts.",
|
||||
"min": 1,
|
||||
"max": 180,
|
||||
"options": None,
|
||||
},
|
||||
{
|
||||
"key": "insurance_expiry_alert_days",
|
||||
"type": "int",
|
||||
"default": 30,
|
||||
"label": "Insurance Expiry Alert Lead Days",
|
||||
"description": "Days prior to insurance policy end date to trigger renewal alerts.",
|
||||
"min": 1,
|
||||
"max": 180,
|
||||
"options": None,
|
||||
},
|
||||
{
|
||||
"key": "calibration_due_window_days",
|
||||
"type": "int",
|
||||
"default": 15,
|
||||
"label": "Calibration Due Window (Days)",
|
||||
"description": "Days before calibration due date when status transitions from upcoming to due.",
|
||||
"min": 1,
|
||||
"max": 90,
|
||||
"options": None,
|
||||
},
|
||||
{
|
||||
"key": "pm_due_window_days",
|
||||
"type": "int",
|
||||
"default": 15,
|
||||
"label": "PM Due Window (Days)",
|
||||
"description": "Days before planned PM date when status transitions from upcoming to due.",
|
||||
"min": 1,
|
||||
"max": 90,
|
||||
"options": None,
|
||||
},
|
||||
{
|
||||
"key": "critical_complaint_sla_hours",
|
||||
"type": "int",
|
||||
"default": 4,
|
||||
"label": "Critical Complaint Response SLA (Hours)",
|
||||
"description": "Target hours to attend and restore a critical priority breakdown complaint.",
|
||||
"min": 1,
|
||||
"max": 72,
|
||||
"options": None,
|
||||
},
|
||||
{
|
||||
"key": "non_critical_complaint_sla_hours",
|
||||
"type": "int",
|
||||
"default": 24,
|
||||
"label": "Non-Critical Complaint Response SLA (Hours)",
|
||||
"description": "Target hours to attend and restore a non-critical priority complaint.",
|
||||
"min": 1,
|
||||
"max": 168,
|
||||
"options": None,
|
||||
},
|
||||
{
|
||||
"key": "escalation_open_complaint_hours",
|
||||
"type": "int",
|
||||
"default": 24,
|
||||
"label": "Open Critical Complaint Escalation (Hours)",
|
||||
"description": "Hours after registration before an unclosed critical complaint triggers escalation.",
|
||||
"min": 1,
|
||||
"max": 168,
|
||||
"options": None,
|
||||
},
|
||||
{
|
||||
"key": "demo_return_alert_days",
|
||||
"type": "int",
|
||||
"default": 3,
|
||||
"label": "Demo Equipment Return Lead Days",
|
||||
"description": "Days before expected return date to alert on demo equipment return.",
|
||||
"min": 0,
|
||||
"max": 30,
|
||||
"options": None,
|
||||
},
|
||||
{
|
||||
"key": "require_closure_remarks",
|
||||
"type": "bool",
|
||||
"default": True,
|
||||
"label": "Require Complaint Closure Remarks",
|
||||
"description": "Require closure remarks before marking a breakdown complaint as closed.",
|
||||
"min": None,
|
||||
"max": None,
|
||||
"options": None,
|
||||
},
|
||||
{
|
||||
"key": "asset_code_prefix",
|
||||
"type": "str",
|
||||
"default": "PHRC",
|
||||
"label": "Asset Code Prefix (used in bulk-import template sample row only)",
|
||||
"description": "Sample code prefix shown in the bulk-import template sample row (e.g. PHRC-ICU-0001). Hand-typed asset codes are not restricted.",
|
||||
"min": None,
|
||||
"max": None,
|
||||
"options": None,
|
||||
},
|
||||
{
|
||||
"key": "default_pm_mode",
|
||||
"type": "enum",
|
||||
"default": "in_house",
|
||||
"label": "Default PM Service Mode",
|
||||
"description": "Default preventive maintenance execution mode when creating new schedules.",
|
||||
"min": None,
|
||||
"max": None,
|
||||
"options": ["in_house", "outsourced"],
|
||||
},
|
||||
{
|
||||
"key": "complaint_no_prefix",
|
||||
"type": "str",
|
||||
"default": "CMP",
|
||||
"label": "Complaint Number Prefix",
|
||||
"description": "Prefix used when generating sequential breakdown complaint numbers (e.g. CMP-2026-0001).",
|
||||
"min": None,
|
||||
"max": None,
|
||||
"options": None,
|
||||
},
|
||||
{
|
||||
"key": "critical_complaint_sets_under_repair",
|
||||
"type": "bool",
|
||||
"default": True,
|
||||
"label": "Critical Complaint Marks Asset Under Repair",
|
||||
"description": "Automatically set asset status to under_repair when a critical breakdown complaint is registered or reopened.",
|
||||
"min": None,
|
||||
"max": None,
|
||||
"options": None,
|
||||
},
|
||||
{
|
||||
"key": "response_start",
|
||||
"type": "enum",
|
||||
"default": "registered_at",
|
||||
"label": "Response Time Start Milestone",
|
||||
"description": "Timestamp used as the starting point for biomedical response time calculation.",
|
||||
"min": None,
|
||||
"max": None,
|
||||
"options": ["registered_at", "received_at"],
|
||||
},
|
||||
{
|
||||
"key": "downtime_end_milestone",
|
||||
"type": "enum",
|
||||
"default": "restored_at",
|
||||
"label": "Downtime End Milestone",
|
||||
"description": "Milestone timestamp that stops the equipment downtime clock.",
|
||||
"min": None,
|
||||
"max": None,
|
||||
"options": ["attended_at", "restored_at", "closed_at"],
|
||||
},
|
||||
{
|
||||
"key": "pm_inhouse_lead_days",
|
||||
"type": "int",
|
||||
"default": 15,
|
||||
"label": "In-House PM Lead Days",
|
||||
"description": "Days before planned in-house PM date when status transitions from upcoming to due.",
|
||||
"min": 1,
|
||||
"max": 90,
|
||||
"options": None,
|
||||
},
|
||||
{
|
||||
"key": "pm_outsourced_lead_days",
|
||||
"type": "int",
|
||||
"default": 15,
|
||||
"label": "Outsourced PM Lead Days",
|
||||
"description": "Days before planned outsourced PM date when status transitions from upcoming to due.",
|
||||
"min": 1,
|
||||
"max": 90,
|
||||
"options": None,
|
||||
},
|
||||
{
|
||||
"key": "calibration_lead_days",
|
||||
"type": "int",
|
||||
"default": 15,
|
||||
"label": "Calibration Lead Days",
|
||||
"description": "Days before calibration due date when status transitions from upcoming to due.",
|
||||
"min": 1,
|
||||
"max": 90,
|
||||
"options": None,
|
||||
},
|
||||
{
|
||||
"key": "red_threshold_days",
|
||||
"type": "int",
|
||||
"default": 7,
|
||||
"label": "Critical Alert Threshold Days",
|
||||
"description": "Days remaining at or below which a due schedule alert escalates to critical (red).",
|
||||
"min": 1,
|
||||
"max": 60,
|
||||
"options": None,
|
||||
},
|
||||
{
|
||||
"key": "scheduled_hours_per_day",
|
||||
"type": "int",
|
||||
"default": 24,
|
||||
"label": "Scheduled Equipment Hours Per Day",
|
||||
"description": "Scheduled daily operating hours per asset used for Monthly Maintenance uptime/downtime calculations.",
|
||||
"min": 1,
|
||||
"max": 24,
|
||||
"options": None,
|
||||
},
|
||||
{
|
||||
"key": "alert_repeat_days",
|
||||
"type": "int",
|
||||
"default": 3,
|
||||
"label": "Overdue Alert Reminder Repeat Days",
|
||||
"description": "Interval in days to repeat notifications for active overdue breakdown and maintenance alerts.",
|
||||
"min": 1,
|
||||
"max": 30,
|
||||
"options": None,
|
||||
},
|
||||
{
|
||||
"key": "smtp_enabled",
|
||||
"type": "bool",
|
||||
"default": False,
|
||||
"label": "Enable Email Notifications (SMTP)",
|
||||
"description": "Enable automated email delivery for high-severity alerts once mail server is configured.",
|
||||
"min": None,
|
||||
"max": None,
|
||||
"options": None,
|
||||
},
|
||||
{
|
||||
"key": "smtp_host",
|
||||
"type": "str",
|
||||
"default": "",
|
||||
"label": "SMTP Host",
|
||||
"description": "Hospital outbound mail server hostname (e.g. smtp.poonahospital.org).",
|
||||
"min": None,
|
||||
"max": None,
|
||||
"options": None,
|
||||
},
|
||||
{
|
||||
"key": "smtp_port",
|
||||
"type": "int",
|
||||
"default": 587,
|
||||
"label": "SMTP Port",
|
||||
"description": "SMTP port (usually 587 for STARTTLS or 465 for SSL).",
|
||||
"min": 1,
|
||||
"max": 65535,
|
||||
"options": None,
|
||||
},
|
||||
{
|
||||
"key": "smtp_from_email",
|
||||
"type": "str",
|
||||
"default": "ams-alerts@poonahospital.org",
|
||||
"label": "SMTP From Email Address",
|
||||
"description": "Sender email address displayed on alert notifications.",
|
||||
"min": None,
|
||||
"max": None,
|
||||
"options": None,
|
||||
},
|
||||
{
|
||||
"key": "comparison_horizon_years",
|
||||
"type": "int",
|
||||
"default": 5,
|
||||
"label": "Cost Comparison Horizon (Years)",
|
||||
"description": "Projection horizon in years for In-House vs Outsourced vs Rent cost comparisons.",
|
||||
"min": 1,
|
||||
"max": 15,
|
||||
"options": None,
|
||||
},
|
||||
{
|
||||
"key": "latest_equipment_count",
|
||||
"type": "int",
|
||||
"default": 10,
|
||||
"label": "Latest Equipment Comparison Count",
|
||||
"description": "Number of most recently installed/purchased assets shown in the AI cost comparison table.",
|
||||
"min": 3,
|
||||
"max": 50,
|
||||
"options": None,
|
||||
},
|
||||
{
|
||||
"key": "default_useful_life_years",
|
||||
"type": "int",
|
||||
"default": 10,
|
||||
"label": "Default Useful Life (Years)",
|
||||
"description": "Fallback useful life in years for depreciation when neither asset nor category specifies one.",
|
||||
"min": 1,
|
||||
"max": 50,
|
||||
"options": None,
|
||||
},
|
||||
{
|
||||
"key": "default_salvage_pct",
|
||||
"type": "float",
|
||||
"default": 5.0,
|
||||
"label": "Default Salvage Value (%)",
|
||||
"description": "Default residual salvage value percentage (0-50%) used in depreciation calculations.",
|
||||
"min": 0,
|
||||
"max": 50,
|
||||
"options": None,
|
||||
},
|
||||
{
|
||||
"key": "default_depreciation_method",
|
||||
"type": "enum",
|
||||
"default": "straight_line",
|
||||
"label": "Default Depreciation Method",
|
||||
"description": "Default asset depreciation formula when an asset does not override it.",
|
||||
"min": None,
|
||||
"max": None,
|
||||
"options": ["straight_line", "written_down"],
|
||||
},
|
||||
{
|
||||
"key": "repeat_failure_count",
|
||||
"type": "int",
|
||||
"default": 3,
|
||||
"label": "Repeat Failure Threshold (Count)",
|
||||
"description": "Minimum breakdown count within the repeat failure window to flag an asset as a repeat failure.",
|
||||
"min": 2,
|
||||
"max": 20,
|
||||
"options": None,
|
||||
},
|
||||
{
|
||||
"key": "repeat_failure_days",
|
||||
"type": "int",
|
||||
"default": 90,
|
||||
"label": "Repeat Failure Window (Days)",
|
||||
"description": "Rolling lookback window in days (from effective today) for counting repeat breakdowns.",
|
||||
"min": 7,
|
||||
"max": 365,
|
||||
"options": None,
|
||||
},
|
||||
{
|
||||
"key": "replacement_review_ratio",
|
||||
"type": "float",
|
||||
"default": 0.4,
|
||||
"label": "Replacement Review Maintenance Ratio",
|
||||
"description": "Cumulative maintenance cost to purchase value ratio (e.g. 0.4 = 40%) that triggers a replacement review flag.",
|
||||
"min": 0.05,
|
||||
"max": 2.0,
|
||||
"options": None,
|
||||
},
|
||||
{
|
||||
"key": "ai_enabled",
|
||||
"type": "bool",
|
||||
"default": True,
|
||||
"label": "Enable Local AI Narrative Summaries",
|
||||
"description": "Allow the configured local AI provider to generate narrative text for AI report metrics (falls back to rule-based text if disabled or unreachable).",
|
||||
"min": None,
|
||||
"max": None,
|
||||
"options": None,
|
||||
},
|
||||
]
|
||||
|
||||
SETTINGS_BY_KEY: dict[str, dict[str, Any]] = {item["key"]: item for item in SETTINGS_SCHEMA}
|
||||
|
||||
|
||||
def validate_setting_value(key: str, value: Any) -> Any:
|
||||
if key not in SETTINGS_BY_KEY:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail=f"Unknown setting key: '{key}'",
|
||||
)
|
||||
spec = SETTINGS_BY_KEY[key]
|
||||
stype = spec["type"]
|
||||
|
||||
if stype == "int":
|
||||
if isinstance(value, bool) or not isinstance(value, int):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail=f"Setting '{key}' must be an integer.",
|
||||
)
|
||||
if spec["min"] is not None and value < spec["min"]:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail=f"Setting '{key}' must be >= {spec['min']}.",
|
||||
)
|
||||
if spec["max"] is not None and value > spec["max"]:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail=f"Setting '{key}' must be <= {spec['max']}.",
|
||||
)
|
||||
return value
|
||||
|
||||
if stype == "float":
|
||||
if isinstance(value, bool) or not isinstance(value, (int, float)):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail=f"Setting '{key}' must be a number.",
|
||||
)
|
||||
fval = float(value)
|
||||
if spec["min"] is not None and fval < spec["min"]:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail=f"Setting '{key}' must be >= {spec['min']}.",
|
||||
)
|
||||
if spec["max"] is not None and fval > spec["max"]:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail=f"Setting '{key}' must be <= {spec['max']}.",
|
||||
)
|
||||
return fval
|
||||
|
||||
if stype == "bool":
|
||||
if not isinstance(value, bool):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail=f"Setting '{key}' must be a boolean.",
|
||||
)
|
||||
return value
|
||||
|
||||
if stype == "enum":
|
||||
if not isinstance(value, str) or value not in (spec["options"] or []):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail=f"Setting '{key}' must be one of {spec['options']}.",
|
||||
)
|
||||
return value
|
||||
|
||||
if stype == "str":
|
||||
if not isinstance(value, str) or not value.strip():
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail=f"Setting '{key}' must be a non-empty string.",
|
||||
)
|
||||
return value.strip()
|
||||
|
||||
if stype == "date_or_empty":
|
||||
if value is None or value == "":
|
||||
return ""
|
||||
if not isinstance(value, str):
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail=f"Setting '{key}' must be a YYYY-MM-DD date string or empty.",
|
||||
)
|
||||
cleaned = value.strip()
|
||||
if cleaned == "":
|
||||
return ""
|
||||
try:
|
||||
date.fromisoformat(cleaned)
|
||||
except ValueError:
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail=f"Setting '{key}' must be a valid YYYY-MM-DD date.",
|
||||
)
|
||||
return cleaned
|
||||
|
||||
raise HTTPException(
|
||||
status_code=status.HTTP_422_UNPROCESSABLE_ENTITY,
|
||||
detail=f"Unsupported setting type for '{key}'.",
|
||||
)
|
||||
|
||||
|
||||
def ensure_default_settings(db: Session) -> None:
|
||||
existing_rows = {row.key: row for row in db.query(Setting).all()}
|
||||
for spec in SETTINGS_SCHEMA:
|
||||
if spec["key"] not in existing_rows:
|
||||
db.add(
|
||||
Setting(
|
||||
key=spec["key"],
|
||||
value_json=json.dumps(spec["default"]),
|
||||
updated_at=utc_now(),
|
||||
)
|
||||
)
|
||||
elif spec["key"] == "ai_enabled":
|
||||
# AI is always on; update legacy false values
|
||||
row = existing_rows["ai_enabled"]
|
||||
if row.value_json in ("false", "False", "0"):
|
||||
row.value_json = json.dumps(True)
|
||||
row.updated_at = utc_now()
|
||||
db.flush()
|
||||
|
||||
|
||||
def get_setting_value(db: Session, key: str, default: Any = None) -> Any:
|
||||
if key == "ai_enabled":
|
||||
return True
|
||||
spec = SETTINGS_BY_KEY.get(key)
|
||||
row = db.query(Setting).filter(Setting.key == key).first()
|
||||
if row is None:
|
||||
return spec["default"] if spec else default
|
||||
try:
|
||||
return json.loads(row.value_json)
|
||||
except (ValueError, TypeError):
|
||||
return spec["default"] if spec else default
|
||||
|
||||
|
||||
def get_demo_as_of_date(db: Session) -> str | None:
|
||||
val = get_setting_value(db, "demo_as_of_date")
|
||||
if isinstance(val, str) and val.strip():
|
||||
return val.strip()
|
||||
return None
|
||||
|
||||
|
||||
def get_all_settings(db: Session) -> list[dict[str, Any]]:
|
||||
rows = {row.key: row for row in db.query(Setting).all()}
|
||||
items: list[dict[str, Any]] = []
|
||||
for spec in SETTINGS_SCHEMA:
|
||||
row = rows.get(spec["key"])
|
||||
value = spec["default"]
|
||||
if row is not None:
|
||||
try:
|
||||
value = json.loads(row.value_json)
|
||||
except (ValueError, TypeError):
|
||||
value = spec["default"]
|
||||
items.append(
|
||||
{
|
||||
"key": spec["key"],
|
||||
"value": value,
|
||||
"type": spec["type"],
|
||||
"label": spec["label"],
|
||||
"description": spec["description"],
|
||||
"default": spec["default"],
|
||||
"min": spec["min"],
|
||||
"max": spec["max"],
|
||||
"options": spec["options"],
|
||||
}
|
||||
)
|
||||
return items
|
||||
|
||||
|
||||
def update_settings(db: Session, values: dict[str, Any], user_id: int | None = None) -> list[dict[str, Any]]:
|
||||
for key, raw_val in values.items():
|
||||
clean_val = validate_setting_value(key, raw_val)
|
||||
serialized = json.dumps(clean_val)
|
||||
row = db.query(Setting).filter(Setting.key == key).first()
|
||||
if row is None:
|
||||
row = Setting(
|
||||
key=key,
|
||||
value_json=serialized,
|
||||
updated_at=utc_now(),
|
||||
updated_by_id=user_id,
|
||||
)
|
||||
db.add(row)
|
||||
else:
|
||||
row.value_json = serialized
|
||||
row.updated_at = utc_now()
|
||||
row.updated_by_id = user_id
|
||||
db.commit()
|
||||
return get_all_settings(db)
|
||||
Reference in New Issue
Block a user