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.xyzhospital.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@xyzhospital.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)