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", "description": "Default prefix used when formatting hospital asset codes (e.g. PHRC-ICU-0001).", "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, }, ] 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 == "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 = {row.key for row in db.query(Setting.key).all()} for spec in SETTINGS_SCHEMA: if spec["key"] not in existing: db.add( Setting( key=spec["key"], value_json=json.dumps(spec["default"]), updated_at=utc_now(), ) ) db.flush() def get_setting_value(db: Session, key: str, default: Any = None) -> Any: 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)