22 KiB
22 KiB
Assumptions Log — XYZ Hospital AMS
Items marked "to be confirmed" or left flexible in the proposal are recorded here along with the configurable defaults implemented in Phase 1.
- Contract Expiry Alert Thresholds: Default alert lead time is
30days (contract_expiry_alert_days), with critical (red) escalation at7days (contract_critical_alert_days). Both are admin-editable in Settings. - Warranty & Insurance Expiry Lead Days: Default alert window is
30days prior to end date (warranty_expiry_alert_days,insurance_expiry_alert_days), configurable by System Admin. - PM & Calibration Due Windows: Planned PM and Calibration items transition from
upcomingtodueat15days beforedue_date/planned_date(calibration_due_window_days,pm_due_window_days), and becomeoverdueonce past the due date. Onlycompleted(andrescheduledfor PM) are persisted in the DB;upcoming/due/overdueare computed at read time againsteffective_today(). - Complaint SLA & Escalation Thresholds: Default target response/restoration SLA is
4hours forcriticalpriority (critical_complaint_sla_hours) and24hours fornon_critical(non_critical_complaint_sla_hours), with unclosed critical complaints escalating after24hours (escalation_open_complaint_hours). - Complaint Closure Remarks:
require_closure_remarksdefaults totrueso engineers must document closure notes before closing a breakdown call; configurable in Settings. - Asset Code Format: Asset codes follow
<asset_code_prefix>-<DEPT_CODE>-<0001>with default prefixPHRC(asset_code_prefix), e.g.PHRC-ICU-0001. - Default PM Service Mode: New PM schedules default to
in_house(default_pm_mode, enumin_house|outsourced). - Demo Equipment Return Alert: Expected return alerts trigger
3days beforeexpected_return_date(demo_return_alert_days), configurable in Settings. - Demo Clock (
demo_as_of_date): System-wideeffective_today()readsdemo_as_of_date(YYYY-MM-DD) from Settings if non-empty; otherwise uses the real current date inAsia/Kolkata. - Soft Deletion for Masters & Users: Deleting departments, locations, categories, vendors, or users sets
is_active = Falserather than hard-deleting rows so historical asset/complaint/maintenance foreign keys remain intact. - Password Hashing on Python 3.13:
passlib==1.7.4is incompatible withbcrypt>=4.1on Python 3.13 (__about__attribute removed / 72-byte wrap-check error), soapp/core/security.pyusesbcrypt(bcrypt==5.0.0) directly.
Assumptions added post-Phase-8
- Permission Specifics:
system_adminandbiomedicalcan create and edit full asset records (coordinatoris restricted to updatingrequires_calibration,insurance_applicable, andremarks). Calibration frequency edits and plan approvals are restricted tosystem_admin,management, andcoordinator(biomedicalreceives HTTP403).department_useris scoped to their assigned department (ICUin demo data) across assets, complaints, PM, calibration, contracts, notifications, dashboard, reports, and global search, whereassystem_admin,biomedical,management, andcoordinatorview all departments hospital-wide.managementandcoordinatorcannot raise complaints (enforced server-side with HTTP403). - Critical Complaint Escalation & SLA Evaluation: APScheduler runs
alerts.pydaily (default06:00in configuredTIMEZONE) and raisescritical_complaintnotifications when open critical complaint age exceedsescalation_open_complaint_hours(default24h) or breachescompute_sla_statusagainstcritical_complaint_sla_hours(default4h) /non_critical_complaint_sla_hours(default24h). - Insurance Drawer: Insurance summary is surfaced via a read-only slide-over panel (
InsuranceDrawer) fromAssetDetailPage,AssetPicker, andComplaintDetailPage; creating and editing policies is handled via modal dialogs on/insuranceand the Asset Insurance tab. - Demo-Only Features: The TopBar Demo Clock (
demo_as_of_date, admin-only date override for demonstrating expiry/overdue alerts and dynamic schedule transitions) and the deterministic seed loader (python -m app.seed.seed) exist specifically for demonstration and verification. - Reopen Clears
restored_at: Reopening a closed breakdown complaint clears bothclosed_atandrestored_at(None) on the complaint row so downtime resumes as ongoing until re-restored. - Immediate Asset Return to Service: When a breakdown complaint is restored or closed (and no other unrestored critical complaints exist on the asset),
Asset.statustransitions immediately toin_servicerather than requiring an extra post-repair sign-off step. - Code Prefixes (
complaint_no_prefix&asset_code_prefix): Complaint numbers are auto-generated usingcomplaint_no_prefix(defaultCMP, e.g.CMP-2026-0001;BD-or another prefix can be configured in Settings). Asset codes are entered manually to match physical hospital asset tags rather than auto-generated, soasset_code_prefix(defaultPHRC) acts as a configurable hospital label prefix shown in Settings and used for the bulk-import template sample code. - Monthly Maintenance
Uptime %Display: Themonthly-maintenancebackend report aggregates uptime/downtime in minutes per department rather than returning per-assetuptime_seconds/downtime_seconds, soUptime %(uptime / (uptime + downtime) * 100, 1 decimal place) is computed on the frontend inReportDetailPage.tsx(falling back to100 - downtime_pct) and highlighted in the summary strip and table. - Attachment & Data Retention Policy (§4.9, §8): In accordance with NABH digital hospital management standards and Indian statutory medical equipment documentation regulations, all equipment service history, breakdown complaint logs, preventive maintenance records, calibration certificates, and uploaded files (PDF/JPG/PNG up to 10 MB) are retained for a minimum mandatory period of 7 years from creation. Condemned and decommissioned equipment records are permanently maintained in read-only archive status and are never hard-deleted, ensuring unbroken historical auditability. Attachments are stored under
backend/data/uploads/with UUID filenames and served strictly through authenticated, role-gated download endpoints. Automated backups (backend/scripts/backup.py) bundle both the database and attachments into timestamped archives with configurable rolling retention (default: 7 copies). - Master Enums vs Editable Tables (§8): Critical operational dimensions — complaint
priority(critical,non_critical), complaintcall_status(open,in_progress,closed), equipmentstatus(in_service,under_repair,condemned,out_of_service), and contract types (AMC,CMC,OTHER) — are intentionally implemented as strict code-enforced Python/TypeScript enums rather than dynamically editable master tables. This design protects the business calculation engine (downtime/uptime percentages, SLA timers, asset status transitions) against data corruption or undefined states that arbitrary user renames could cause. - Client Sign-Off & Default Thresholds (§4.3, §4.8, §5, §6): The hospital administration configures and approves operational thresholds via the
/settingsmanagement console:critical_complaint_sla_hours: default 4 hours.non_critical_complaint_sla_hours: default 24 hours.escalation_open_complaint_hours: default 24 hours.contract_expiry_alert_days: default 30 days (red critical threshold: 7 days).calibration_due_window_days: default 15 days.pm_inhouse_lead_days: default 7 days;pm_outsourced_lead_days: default 15 days.require_closure_remarks: default True.downtime_milestone: defaultrestoration(downtime terminates when equipment is restored).
- Alert Recurrence & Notification Re-trigger Policy (§6): The alert engine runs daily at 06:00 Asia/Kolkata and employs deterministic deduplication keys (
dedupe_key) to prevent duplicate in-app notifications on consecutive days while a condition remains active. Overdue alerts escalate in severity tored, and an optional repeat reminder interval (alert_repeat_days, default 3 days) re-notifies coordinators and biomedical teams until the underlying task (PM, calibration, contract renewal, or breakdown) is addressed. SMTP email dispatch can be enabled in settings when hospital IT confirms mail server credentials. - Duplicate Record & Import Conflict Prevention (Task 1):
- Contracts: A duplicate contract is defined by
(asset_id, contract_type, start_date, end_date)matching any existing contract in the database (including superseded ones).POST /api/contractsrejects exact duplicates with HTTP 409 (A contract with the same asset, type and dates already exists.). Contract renewals viaPOST /api/contracts/{id}/renewremain unaffected. In bulk import, in-file duplicate rows receiveDuplicate of row N in this file.and rows duplicating database records receiveAlready exists in the system.. - Insurance Policies: A duplicate insurance policy is defined by trimmed, case-insensitive
policy_nomatching any existing policy in the database.POST /api/insurancerejects duplicates with HTTP 409 (Policy number already exists.). In bulk import, in-file duplicate rows receiveDuplicate of row N in this file.and rows duplicating database records receiveAlready exists in the system.. - Calibration Plans: Each asset can have at most one calibration plan. In bulk import, rows for assets that already have a calibration plan in the database receive
Asset already has a calibration plan., while rows repeating an earlier row for the same asset in the same upload file receiveDuplicate of row N in this file.. Dry run previews surface these validation errors identically.
- Contracts: A duplicate contract is defined by
- Import Template Multi-Sheet Structure (Task 2): All four bulk-import templates (Assets, Contracts, Calibration Plans, Insurance Policies) feature an empty data template on Sheet 1 (containing only styled headers), an 'Example' reference on Sheet 2 (with warning banner 'Example only - this sheet is ignored on import' in Row 1 and sample values in Row 2), and 'Master Reference' lookup tables on Sheet 3. All four importers read strictly the first worksheet (
wb.worksheets[0]), ensuring sample rows and reference sheets are never accidentally imported. - Backup Script Path Resolution & Dual Archive Packaging (Task 3):
backend/scripts/backup.pyexposesget_db_path(db_url, backend_dir)to accurately resolve SQLite file paths fromDATABASE_URLacross relative paths (sqlite:///./data/ams.db,sqlite:///data/ams.db), absolute POSIX/Windows paths (sqlite:////app/data/ams.db,sqlite:////tmp/x/custom.db), and in-memory or fallback scenarios.create_backup()supports both.tar.gzand.ziparchives and packages SQLite database files under bothdb.sqlite3andams.dbmember names for cross-environment compatibility. - Universal Password Policy (Task 4): A unified validation rule (
validate_password) is enforced across user registration, profile updates, self-service password changes, and administrator resets:- Length: 8 to 128 characters.
- Character composition: at least one letter and at least one digit (case-insensitive; special characters permitted).
- Whitespace: leading and trailing spaces are strictly prohibited and rejected with HTTP 422 (never silently trimmed).
- Prohibited passwords: blocklist of common passwords (
123456,12345678,password,password1,qwerty123,admin123,welcome1), while preservingdemo@123for seeded testing environments. - Username containment: cannot contain the user's email username (local part before
@) if 4 or more characters. - Password changes additionally require that the new password is not identical to the current password.
- Admin Reset Password Interface (Task 5):
frontend/src/api/users.tsandfrontend/src/pages/MastersPage.tsxexpose an administrator password reset modal for users with rolesystem_admin. The dialog features password masking toggles, client-side mismatch validation (Passwords do not match), universal password policy helper instructions, and displays backend 422 validation errors inline. Successful resets trigger a notification toast and close the modal without affecting the active administrator session. - Department User Scoping & Empty Scope Resolution (Task 6):
backend/app/services/scoping.pyimplementsresolve_department_scope(user, requested_dept_id). Non-department roles are unconstrained and may optionally filter byrequested_dept_id. Assigneddepartment_useraccounts are strictly bound touser.department_id, ignoring any client-requested department parameter. Unassigneddepartment_useraccounts (department_id=None) resolve tois_empty=True, immediately returning 0 counters on Dashboard summary, empty results on global search, and empty row lists across all accessible report endpoints without running hospital-wide queries. Report key aliases are registered to support both canonical paths and audit identifiers (e.g.,equipment-inventory,condemned-equipment,pm-schedule). - Token Versioning & Session Invalidation (Task 7): A
token_versioninteger column (default 0, not null) is added tousersand reconciled automatically viarun_sqlite_migrations. Access tokens encode the user'stoken_versionin claim"tv".get_current_userrejects tokens with mismatched"tv"with HTTP 401 (Token has been invalidated. Please log in again.). Password changes and administrator password resets incrementuser.token_version, invalidating previous tokens.POST /api/auth/change-passwordreturns a renewed access token, andChangePasswordModal.tsxstores the new token in the active auth store to keep the user's session active without re-login. - Delivery Cleanliness, Line Endings & Packaging (Task 8):
.gitattributesenforces standard LF line endings across the repository (* text=auto eol=lf)..gitignoreexcludes all SQLite databases (*.db), backups, volatile uploads, frontend dist artifacts, and build info files. Themake packagetarget generates../xyz-ams-delivery.zipusinggit archiveto ensure zero uncommitted, ignored, or temporary files leak into handoff archives. - Cost Fields & Role-Based Stripping (AI Task 1): The fields
purchase_value,monthly_rent,contract_value,cost_per_visit,repair_cost, andspare_cost_estimateare classified as cost fields. Fordepartment_user, these keys are completely stripped from JSON responses across/api/assets,/api/contracts,/api/pm/schedules, and/api/complaintsviamaybe_strip_costs_response. For contract bulk imports, both the canonicalcontract_valueheader and legacycostalias are accepted for backward compatibility.settings_servicesupports a typedfloatsetting type fordefault_salvage_pct(0–50) andreplacement_review_ratio(0.05–2.0). - AMC/CMC Auto-Tagging & Outsourced PM Auto-Fill (AI Task 2): Coverage precedence is strictly
active warranty > active CMC > active AMC > active OTHER contract > out_of_contractwhere active meansstart_date <= on_date <= end_dateandis_superseded == False. When registering a complaint, coverage is snapshotted as ofeffective_today(db)intocoverage_tag,coverage_contract_id, andcoverage_provider_idso historical registration coverage remains immutable even after contracts expire, whilecoverage_nowalways reflects live coverage. Creating an outsourced PM schedule withoutprovider_id/contract_idauto-fills them from the asset's highest-priority active AMC/CMC contract (CMC over AMC); if none exists, the schedule is still created with empty provider/contract and"no_active_contract": truewarning (replacing the legacy 422 rejection). - Metrics Engine Formulas & Edge Cases (AI Task 3):
- Depreciation: Uses
years_elapsed = max(0, (as_of - (installation_date or purchase_date)).days / 365.25). Forwritten_downwithsalvage_pct == 0, an effective salvage floor ratio of0.01is used to compute the declining-balance rate while clamping book value at 0. Rented assets returnapplicable=False, reason="rented". - Scenario Comparison: For 1-year contracts spanning 364–366 days inclusive,
contract_years = 1.0so annual contract cost equals the contract value cleanly without leap-day distortion. When the latest contract isCMC,spare_cost_estimateis excluded from Scenario B's annual breakdown cost whilerepair_costis retained (CMC covers spare parts). Missing required inputs mark that scenario"Insufficient data: <input>"and never coerce to zero. "Latest equipment" is defined as the toplatest_equipment_countassets (default10, configurable 3–50) ordered by most recentinstallation_date(falling back topurchase_date) within the active department/category filter. - Efficiency: Weights are centralized in
EFFICIENCY_WEIGHTS(uptime=0.50, pm_compliance=0.20, response=0.15, repeat_free=0.15). Condemned assets are excluded from operational efficiency (matching Monthly Maintenance). When an asset has zero PM records due in the selected period or zero attended complaints, its PM compliance or response sub-score defaults to 100.0 so assets without scheduled PM or breakdowns are not penalized. Department and category efficiency scores are weighted averages of their assets weighted by scheduled operating minutes.
- Depreciation: Uses
- AI Provider Layer, Grounding Validation, Privacy & Caching (AI Task 5):
- Privacy:
build_prompt()strictly whitelists only structured metric fields (id,label,value,unit,formatted) and structured suggestion fields (id,rule,severity,asset_codes,evidence_metric_ids,action_for_human), stripping any extra keys and redacting email patterns so user names, emails, complaint descriptions, and free-text remarks are never transmitted to any model. Prompts and responses are never logged atINFOlevel. - Number Grounding Check: Before extracting numeric values from model output for 0.5% tolerance verification against evidence, known asset codes (
PHRC-DEPT-0001), metric IDs (m_...), and rule codes (S1–S8) are stripped so identifier digits are not misclassified as invented numbers. - Cache Key:
ai_summariescaches narratives keyed by(section, filters_hash, data_hash)wherefilters_hashincorporates the active AI mode/provider/model so togglingai_enabledor switching local models automatically refreshes narratives without stale cross-mode hits. Every write creates anAuditLogentry (entity_type="ai_summary").
- Privacy:
- AI Reporting API & 3-Sheet Excel Exports (AI Task 6): All
/api/ai/*endpoints enforce role access viarequire_roles(system_admin, biomedical, management, coordinator)sodepartment_userreceives HTTP 403 across all AI routes (including status and exports), whilePOST /api/ai/narrative/regenerateis restricted strictly tosystem_admin. Both hyphenated (breakdown-frequency) and underscored (breakdown_frequency) section keys are accepted on regenerate and export endpoints. Excel exports reuseservices/exports.pystyling and_sanitize_sheet_titleto produce 3 sheets: the main report sheet,"Evidence", and"How calculated". - AI Report UI Navigation, Asset Links & Settings Grouping (AI Task 7): Sidebar retains a single
Reportsnavigation entry; switching between Simple reports and AI report is handled via a segmented toggle onReportsPageandAIReportPage(hidden fordepartment_user, with/reports/aiguarded byRoleGuard capability="view_ai_reports"). Suggestion asset code badges link directly to/assets/:idwhen the asset is present in loaded section rows, falling back to/assets?search=<code>. OnSettingsPage, the 9 cost/AI settings are grouped under"AI and cost analysis"alongside a read-only runtime status banner fetched from/api/ai/status. - Brand Identity, Design Tokens & Hospital Name (MediAsset AI / XYZ Hospital):
- Hospital Rebranding: Hospital tenant name is designated as XYZ Hospital across application branding, titles, and authentication views.
- Brand Palette: The enterprise color system consists of:
- Clinical Navy (
#102C52): Foundational authority, enterprise permanence, primary navigation backgrounds, executive typography. - Intelligence Blue (
#2E5C9A): Digital intelligence, AI India Innovations proposal alignment, interactive buttons, active tab states. - Medical Teal (
#008E95): MediAsset AI signature accent, telemetry indicator, precision highlights, status badges. - Pale Blue (
#E8EFF7): Soft ergonomic UI surfaces, card borders, subtle backgrounds. - Cloud White (
#F8FAFC): Crisp clinical workspace background.
- Clinical Navy (
- Logo Direction: Vector emblem combines a restrained medical-equipment pulse (ECG wave) with a connected asset/data-network node mesh (
/logo.svg,/logo-mark.svg, fallback/logo.jpg). Avoids generic medical crosses, excessive circuitry, and complex gradients. - Typography: Clean sans-serif family
Interfor digital product and web; Calibri-compatible styling for corporate proposals and executive documentation. - Visual Personality: Precise, reliable, modern, clinical, and enterprise-grade. Product presentations utilize authentic dashboard interfaces, equipment telemetry, and clear data visualizations rather than generic AI robot imagery.
- Clearance Disclaimer: "The name, tagline, logo concept, and palette are proposed brand assets and remain subject to clearance."